Heap sort is selection sort with a better short-term memory. Plain selection sort scans the whole unsorted region to find the maximum, O(n) per round, O(n²) total. Heap sort keeps the unsorted region inside a max-heap, where the maximum is always at the root. Each round it swaps the root to the end of the array (the sorted tail), shrinks the heap by one, and repairs the heap with one sift-down. Finding the maximum drops from O(n) to O(log n), and the total becomes O(n log n).
The whole sort lives inside one array. Heaps are arrays in disguise, children of index i sit at 2i+1 and 2i+2, so no extra buffer is needed. That gives heap sort two properties at once: worst-case O(n log n) time (merge sort's guarantee) and O(1) extra space (quick sort's). Its weakness is locality: heap jumps around the array (i → 2i+1), so CPU caches hate it, and in practice well-tuned quick sort usually beats it on real hardware.
The two phases
- 1
Phase 1, heapify (build the max-heap)
Starting from the last parent (index ⌊n/2⌋ − 1) and walking back to the root, sift each node down. Most subtrees are tiny, so the total work telescopes to O(n), a famous result that surprises everyone the first time.
- 2
Phase 2, extract n − 1 times
Swap the root (max) with the last heap element; the sorted region grows by one from the right. Sift the new root down through the shrinking heap: O(log n) per extraction.
- 3
Finish
After n − 1 extractions the single remaining element is the minimum, already in place. The array is sorted ascending.
- 4
Stability check
The long-distance swaps reorder equal keys, so heap sort is not stable, same caveat as quick and selection sort. Stable O(n log n) needs merge sort (or a clever key trick).
The complete sort in ~20 lines
function heapSort(arr) {
const n = arr.length;
// Phase 1, build max-heap, bottom-up: O(n) total
for (let i = Math.floor(n / 2) - 1; i >= 0; i--) {
siftDown(arr, i, n);
}
// Phase 2, repeatedly move max to the sorted tail: O(n log n)
for (let end = n - 1; end > 0; end--) {
[arr[0], arr[end]] = [arr[end], arr[0]]; // max → final position
siftDown(arr, 0, end); // repair heap of size 'end' (shrinking)
}
return arr;
}
function siftDown(arr, i, size) {
while (true) {
const l = 2 * i + 1, r = 2 * i + 2;
let largest = i;
if (l < size && arr[l] > arr[largest]) largest = l;
if (r < size && arr[r] > arr[largest]) largest = r;
if (largest === i) return;
[arr[i], arr[largest]] = [arr[largest], arr[i]];
i = largest; // continue down that path
}
}Cost summary
| Operation / case | Cost | Notes |
|---|---|---|
| Build heap (bottom-up) | O(n) | the telescoping sum 0·(n/4) + 1·(n/8) + … |
| Each extract-max | O(log n) | one root-to-leaf sift path |
| Full sort | O(n log n) worst/average/best | no adversarial input exists |
Best case is still O(n log n), even a sorted array gets fully heapified. Heap sort never exploits existing order; that is the price of its ironclad guarantee.
Practice
Array [4, 7, 2] becomes what max-heap array after heapify? (comma-separated)
Reveal explanation
Sift the root: children 7 and 2 → largest child 7 > 4, swap → [7, 4, 2]. With n = 3 there is exactly one parent, so heapify is a single swap.