面試常考:如何對陣列進行排序?主要有兩種思路:呼叫 JDK 內建 java.util.Arrays.sort() 或自行實作演算法(如冒泡排序)。本文提供完整可執行程式碼與執行結果對照。
Arrays 類別提供多種陣列操作,sort() 採用優化的快速排序(基本型態)或合併排序(物件),效能優於自行實作的簡單演算法。
package cn.z_xiaofei168.sort;
import java.util.Arrays;
public class TestArraySort {
public static void main(String[] args) {
int[] arr = { -1, -3, 5, 7, 9, 2, 4, 6, 8, 10 };
System.out.print("整數排序前:");
displayIntArr(arr);
Arrays.sort(arr);
System.out.print("整數排序後:");
displayIntArr(arr);
String[] name = {"Tom","Kitty","James","z_xiaofei168","DXL_xiaoli","Zhang_Di"};
System.out.print("字串排序前:");
displayStringArr(name);
Arrays.sort(name);
System.out.print("字串排序後:");
displayStringArr(name);
}
static void displayIntArr(int[] arr) {
for (int i : arr) System.out.print(i + "\t");
System.out.println();
}
static void displayStringArr(String[] arr) {
for (String s : arr) System.out.print(s + "\t");
System.out.println();
}
}

雙層迴圈相鄰比較交換,時間複雜度 O(n²),適合教學理解排序原理,實務上不建議用於大量資料。
package cn.z_xiaofei168.sort;
public class TestMaopao {
public static void main(String[] args) {
int[] arr = { -1, -3, 5, 7, 9, 2, 4, 6, 8, 10 };
System.out.print("整數排序前:");
for (int ar : arr) System.out.print(ar + "\t");
System.out.println();
displayIntArr(arr); // 排序
System.out.print("整數排序後:");
for (int a : arr) System.out.print(a + "\t");
}
/** 冒泡排序 */
static void displayIntArr(int[] arr) {
for (int i = arr.length - 1; i > 0; i--) {
for (int j = 0; j < i; j++) {
if (arr[j] > arr[j + 1]) {
int temp = arr[j];
arr[j] = arr[j + 1];
arr[j + 1] = temp;
}
}
}
}
}

Arrays.sort() 為雙軸快速排序(Java 7+),基本型態平均 O(n log n),且經過大量優化。歡迎留言分享更多排序實作方式,共同學習進步!