簡體   English   中英

無需在Java中使用內置排序方法即可動態排序用戶輸入

[英]Sorting user input dynamically without using inbuilt sorting methods in Java

我試圖排序一些用空格分隔的用戶輸入的整數。

輸入:4 2 1 5 9 - 預期輸出:1 2 4 5 9

用戶在循環中按下回車后我無法弄清楚如何停止循環,其中i <num。 當我逐個輸入整數時,我的代碼會起作用。 任何幫助,將不勝感激

 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]);
}}

你的代碼幾乎是正確的,然后你刪除了你的最佳提示。 使用Scanner.nextInt()類的

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.
}

如此簡單但又高效:

Arrays.sort(array);

您可以使用Bubble sort算法。 它在最壞的情況下運行o(n ^ 2)。 沒有必要把代碼放在這里,你可以做到。 它只需不到20行。

暫無
暫無

聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.

 
粵ICP備18138465號  © 2020-2024 STACKOOM.COM