如何用 Java 排序一個隨機數陣列?


要在 Java 中對陣列進行排序,你需要將陣列的每個元素與剩下的元素進行比較,並驗證它是否更大,如果更大則交換它們。

為此,你需要使用兩個迴圈(巢狀),其中外迴圈變數 i 的內迴圈以 i+1 開始,以避免在比較中重複。

示例

 即時演示

import java.util.Arrays;
import java.util.Scanner;

public class ArrayInOrder {
   public static void main(String args[]) {
      Scanner sc = new Scanner(System.in);
      System.out.println("Enter the size of the array that is to be created::");
      int size = sc.nextInt();
      int[] myArray = new int[size];
      System.out.println("Enter the elements of the array ::");
   
      for(int i = 0; i<size; i++) {
         myArray[i] = sc.nextInt();
      }

      for(int i = 0; i<size-1; i++) {
         for (int j = i+1; j<myArray.length; j++) {
            if(myArray[i] > myArray[j]) {
               int temp = myArray[i];
               myArray[i] = myArray[j];
               myArray[j] = temp;
            }
         }
      }
      System.out.println(Arrays.toString(myArray));
   }
}

輸出

Enter the size of the array that is to be created ::
6
Enter the elements of the array ::
54
63
14
78
2
3
[2, 3, 14, 54, 63, 78]

更新於: 30-Jul-2019

2K+ 瀏覽量

開啟您的職業生涯

完成課程取得認證

開始
廣告
© . All rights reserved.