为什么我的选择排序没有按升序排列数组?

时间:2019-09-16 02:35:43

标签: java arrays selection-sort

import java.util.*;

public class SelectionSort {
    public static void main(String[] args) {

        int[] list = {10, 12, 4, 9, 1};
        int listLength = list.length;

        int minimum;
        int currentNum;
        int minIndex = 0;

        //prints list
        for (int count = 0; count < list.length; count++) {
            System.out.println(list[count]);
        }

        for (int counter = 0; counter < listLength-1; counter++) {
            minimum = list[counter];

            for (int index = counter; index < listLength; index++) {
                currentNum = list[index];

                if (minimum > currentNum) {
                    minimum = currentNum;

                    minIndex = index;
                }
            }

            list[minIndex] = list[counter];
            list[counter] = minimum;

            counter++;
        }

        System.out.println("\nReorganized List: \n");

        for (int count = 0; count < list.length; count++) {
            System.out.println(list[count]);
        }



    }
}

代码输出为1,12,4,9,4。我曾尝试在for循环中遍历数组的长度。该算法应该按升序排列数组,但是我只设法对第一个最小数进行排序,然后算法中断了。

1 个答案:

答案 0 :(得分:0)

您可以使用数组(java.util.Arrays)。请尝试以下操作。

int[] list = {10, 12, 4, 9, 1};
Arrays.sort(list);
for (int i = 0; i < list.length; i++) {
 System.out.println(list[i]);
};