java.util.Arrays 提供高效排序工具,底層採用雙軸快速排序(基本型別)與歸併排序(對象),支援範圍排序、並行排序與自定義比較器。本文全面講解用法、原理與效能特徵。
static void sort(int[] a) // 全量升序
static void sort(int[] a, int from, int to) // 範圍排序 [from, to)
支援所有基本型別:byte, short, int, long, float, double, char。
int[] arr = {5, 2, -1, 8, 0};
Arrays.sort(arr); // [-1, 0, 2, 5, 8]
基本型無直接降序 API,兩種方案:
// 方案一:升序 + 反轉
Arrays.sort(arr);
for (int i = 0, j = arr.length - 1; i < j; i++, j--) {
int tmp = arr[i]; arr[i] = arr[j]; arr[j] = tmp;
}
// 方案二:包裝類 + Comparator(JDK 8+)
Integer[] boxed = Arrays.stream(arr).boxed().toArray(Integer[]::new);
Arrays.sort(boxed, Comparator.reverseOrder());
static void sort(T[] a, Comparator super T> c)
static void sort(T[] a, int from, int to, Comparator super T> c)
class Point {
int x, y;
Point(int x, int y) { this.x = x; this.y = y; }
}
Point[] points = {new Point(2,1), new Point(2,2), new Point(1,2), new Point(0,1)};
// x 升序,x 相同則 y 升序
Arrays.sort(points, (p1, p2) -> {
if (p1.x != p2.x) return Integer.compare(p1.x, p2.x);
return Integer.compare(p1.y, p2.y);
});
// 結果:(0,1) (1,2) (2,1) (2,2)
// 等價於上面 Lambda
Arrays.sort(points,
Comparator.comparingInt((Point p) -> p.x)
.thenComparingInt(p -> p.y));
| 陣列類型 | 算法 | 時間複雜度 | 穩定性 | 空間 |
|---|---|---|---|---|
| 基本型別 | 雙軸快速排序 | O(n log n) 平均 | 不穩定 | O(log n) 棧 |
| 對象/包裝類 | TimSort(歸併變體) | O(n log n) 最壞 | 穩定 | O(n) 輔助陣列 |
設計原因:基本型別無身份認同,不穩定可接受且快排更快;對象需穩定性保證相等元素相對順序,TimSort 利用已有序片段(runs)極適合真實數據。
Arrays.parallelSort(largeArray); // 自動分治多線程,大數據量顯著加速
Arrays.asList() 返回固定長度 List,不可 sort(支援 Collections.sort() 但底層陣列不可變)Double.compare() 而非 d1 - d2(溢出/NaN 問題)