Sort user input dynamically without using built-in sort methods in Java

I am trying to sort some user-entered integers, separated by spaces.

Entrance: 4 2 1 5 9 - Expected result: 1 2 4 5 9

I can’t figure out how to stop the loop after the user presses the input in the loop where I <Num. My code works when I enter 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]);
}}
+4
source share
3 answers

Your code was almost right and you removed the best hint. Use Scanner.nextInt()as

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.
}
+6
source

So simple, but so effective:

Arrays.sort(array);
0
source

You can use the algorithm Bubble sort. In the worst case, it works o (n ^ 2). No need to enter the code here, you can do it. It only takes 20 lines.

0
source

All Articles