Java - Selection Sort Algorithm

后端 未结 17 1648
我在风中等你
我在风中等你 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:49

    What is wrong is that in your inner loop you should update your index, using the strategy you follow of doing the swap in the inner loop I made a working selection sort:

    import java.util.Arrays;
    
    public class SelectionSort {
    
      public static void main(String[] args) {
        int[] input = new int[] {5,2,4,6,1,3};
        System.out.println( Arrays.toString(selectionSort(input)) );
      }
    
      public static int[] selectionSort(int[] input) {
        int length = input.length;
        int minimumValue = Integer.MAX_VALUE;
    
        for (int i = 0; i < length; ++i) {
            // find the minimumValue when j > i and swap it  with input[i] location
            for (int j =i; j < length; ++j) {
              if (input[j] <= minimumValue ) {
                minimumValue = input[j];
                input[j] = input[i];
                input[i] = minimumValue;
              }
            }
            minimumValue = Integer.MAX_VALUE;
        }
        return input;
      }
    
    }
    

    I added to github.

提交回复
热议问题