如何在 Java 中對隨機數陣列進行排序?
要對 Java 中的陣列進行排序,你需要比較陣列中的每個元素和所有剩餘元素,並驗證它們是否更大,如果更大則交換它們。
要做到這一點,一種解決方案是使用兩個迴圈(巢狀迴圈),其中內迴圈從 i+1 開始(其中 i 是外迴圈的變數),以避免比較中的重複。
示例
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]
廣告
資料結構
網路
關係型資料庫管理系統
作業系統
Java
iOS
HTML
CSS
Android
Python
C 程式設計
C++
C#
MongoDB
MySQL
JavaScript
PHP