Java - Selection Sort Algorithm

后端 未结 17 1622
我在风中等你
我在风中等你 2020-12-17 04:26

I have some questions about selection sort.I\'m a little bit confused.

 int [] arr = {5,4,3,2,1}; // This is my array
    int min = 0;

    for(int i = 0;i&l         


        
17条回答
  •  Happy的楠姐
    2020-12-17 04:49

    As mentioned earlier, you're not updating your 'min' variable in the inner loop. The objective of the inner loop is to find the index of the smallest element. You should also move the 'swap' to the outer loop. Below is the Selection Sort pseudo code:

    Selection Sort
    Inputs:
      A: an array
      n: the number of elements in A to sort
    
    Procedure SELECTION-SORT (A, n)
    1. For i = 0 to n – 1:
      A. Set minIndex to i.
      B. For j = i + 1 to n:
        i. If A[j] < A[minIndex], then set minIndex to j. // Add this
      C. Swap A[i] with A[minIndex]. // Move this to outside of the inner loop
    

    Take a look at the link to my blog below to see a full explanation of the Selection Sort algorithm. There are implementations in Java, C++, Python, and JavaScript.

    http://brianredd.com/algorithm/selection-sort

提交回复
热议问题