Java - Selection Sort Algorithm

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

    selection sort is about finding the min value in each step of loop. you didn't find out the min value (by if statement maybe), just simply exchange the value in your inner loop. so you actually didn't do a sort.

    correction based on your implementation:

    final int[] arr = { 5, 4, 3, 2, 1 }; // This is my array
        int min;
        for (int i = 0; i < arr.length; i++) {
            // Assume first element is min
            min = i;
            for (int j = i + 1; j < arr.length; j++) {
                if (arr[j] < arr[min]) {
                    min = j;
    
                }
            }
            if (min != i) {
                final int temp = arr[i];
                arr[i] = arr[min];
                arr[min] = temp;
            }
            System.out.println(arr[i]);// I print the in ascending order
        }
    

    this should give you output:

    1
    2
    3
    4
    5
    

提交回复
热议问题