Java - Selection Sort Algorithm

后端 未结 17 1621
我在风中等你
我在风中等你 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条回答
  •  甜味超标
    2020-12-17 04:54

        int[] arr = {5,4,3,2,1};
    
        for (int i = 0; i < arr.length - 1; i++)
             {
                int index = i;
                  for (int j = i + 1; j < arr.length; j++)
                      if (arr[j] < arr[index]) 
                       index = j;
    
                int smallerNumber = arr[index];  
                arr[index] = arr[i];
                arr[i] = smallerNumber;
          }
    

    This is the correct method for selection sort The thing you have been doing wrong is you are swapping within the inner loop but actually the swapping needs to be done after the first complete round of inner loop where the minimum element is determined.

提交回复
热议问题