maxHeapify,自下而上構建大頂堆;maxHeapify,重複至尺寸為 1;maxHeapify(i) 保證以 i 為根的子樹滿足大頂堆性質,若子節點更大則交換並遞歸向下。public class HeapSort {
private int left(int i) { return 2 * i + 1; }
private int right(int i) { return 2 * i + 2; }
// 維護大頂堆性質
public void maxHeapify(int[] heap, int i, int size) {
int l = left(i), r = right(i), largest = i;
if (l < size && heap[l] > heap[largest]) largest = l;
if (r < size && heap[r] > heap[largest]) largest = r;
if (largest != i) {
swap(heap, i, largest);
maxHeapify(heap, largest, size); // 遞歸向下
}
}
// 建堆
public void buildHeap(int[] heap) {
for (int i = heap.length / 2 - 1; i >= 0; i--) {
maxHeapify(heap, i, heap.length);
}
}
// 堆排序入口
public void sort(int[] heap) {
buildHeap(heap);
for (int i = heap.length - 1; i > 0; i--) {
swap(heap, 0, i); // 最大值換到末尾
maxHeapify(heap, 0, i); // 縮小堆範圍,調整新堆頂
}
}
private void swap(int[] a, int i, int j) {
int t = a[i]; a[i] = a[j]; a[j] = t;
}
public static void main(String[] args) {
int[] arr = {4, 1, 5, 3, 7, 12, 65, 7};
new HeapSort().sort(arr);
System.out.println(Arrays.toString(arr)); // [1, 3, 4, 5, 7, 7, 12, 65]
}
}
| 指標 | 數值 |
|---|---|
| 時間複雜度 | O(n log n) — 最好/最壞/平均一致 |
| 空間複雜度 | O(1) — 原地排序 |
| 穩定性 | 不穩定 |
PriorityQueue 即基於小頂堆。手寫堆排序是理解「完全二叉樹隱式結構 + 自下而上構建 + 原地交換」三位一體設計的最佳練習。