Sorting user input dynamically without using inbuilt sorting methods in Java

时间:2016-07-11 22:50:47

标签: java sorting for-loop bubble-sort

I am trying to sort some user inputted integers separated by spaces.

Input: 4 2 1 5 9 -- Expected output: 1 2 4 5 9

I can't figure out how to stop the loop after the user presses enter in the loop where i < num. My code works when I enter the integers one by one. Any help would be appreciated

 class javasort {
    public static void main(String[] args) {
    int num, i, j, temp;
    Scanner input = new Scanner(System.in);

    // System.out.println("Enter the number of integers to sort:");
    // num = input.nextInt();

    num = 5; // <-- the user input should be dynamic

    int array[] = new int[num];

    System.out.println("Enter integers: ");

    for (i = 0; i < num; i++)

        array[i] = Integer.parseInt(input.next());
        num = i; // make array as big as input ?

    for (i = 0; i < (num - 1); i++) {
        for (j = 0; j < num - i - 1; j++) {
            if (array[j] > array[j + 1]) {
                temp = array[j];
                array[j] = array[j + 1];
                array[j + 1] = temp;
            }
        }
    }

    System.out.println("Sorted list of integers:");

    for (i = 0; i < num; i++)
        System.out.println(array[i]);
}}

3 个答案:

答案 0 :(得分:6)

Your code was very nearly correct, and then you removed the best hint you had. Use Scanner.nextInt() like

num = input.nextInt();          // <-- get the count.
int array[] = new int[num];
System.out.println("Enter integers: ");
for (i = 0; i < num; i++) {     // <-- don't rely on indentation for flow control.
    array[i] = input.nextInt(); // <-- get a number "num" times.
}

答案 1 :(得分:0)

So simple, yet so efficient:

Arrays.sort(array);

答案 2 :(得分:0)

您可以使用Bubble sort算法。它在最坏的情况下运行o(n ^ 2)。没有必要把代码放在这里,你可以做到。它只需不到20行。