本範例展示兩種方式對三個整數由小到大排序:一種使用簡單的氣泡排序邏輯,另一種利用 Arrays.sort() 內建方法。適合初學者理解排序基本原理與 Java 陣列操作。
public class Ex34 {
public static void main(String[] args) {
int[] arrays = {800, 56, 500};
// 氣泡排序:外層控制輪數,內層相鄰比較交換
for (int i = arrays.length; --i >= 0; ) {
for (int j = 0; j < i; j++) {
if (arrays[j] > arrays[j + 1]) {
int temp = arrays[j];
arrays[j] = arrays[j + 1];
arrays[j + 1] = temp;
}
}
}
for (int n = 0; n < arrays.length; n++)
System.out.println(arrays[n]);
}
}
import java.util.Arrays;
public class SortDemo {
public static void main(String[] args) {
int[] nums = {800, 56, 500};
Arrays.sort(nums); // 內部使用 Dual-Pivot Quicksort (基本型別)
for (int n : nums) System.out.println(n);
}
}
| 輪次 | 比較過程 | 陣列狀態 |
|---|---|---|
| 1 | 800>56 交換 → 56,800,500 800>500 交換 → 56,500,800 | 56, 500, 800 |
| 2 | 56>500 不交換 | 56, 500, 800 (已有序) |
public static void sortThree(int a, int b, int c) {
int[] arr = {a, b, c};
Arrays.sort(arr);
System.out.printf("排序結果:%d, %d, %d%n", arr[0], arr[1], arr[2]);
}
i 從 length 遞減至 1,j 從 0 到 i-1。temp = a; a = b; b = temp;。Arrays.sort() 原地排序,回傳 void。