In an emergency room, patients aren't seen in the order they arrived. The most urgent one is called first, and once they're treated, the next most urgent one moves to the front. The nurses don't re-sort every patient each time someone is called.
Heap sort uses the same idea, with the largest number as the most urgent patient. Heap sort takes the largest number again and again and puts it at the back. So that the largest number is always easy to find, the array is first arranged into a heap. Like the nurses, a heap doesn't sort all the numbers. It only keeps the largest at the front.
A heap, then take the largest
A max-heap is an array read as a branching tree. The number at index i has at most two children, at index 2i + 1 and 2i + 2. A number that has children is called a parent. A max-heap has just one rule: every parent is larger than or equal to its children. So the largest number is always at the top of the tree, at index 0, called the root.
Here is a max-heap, as an array and as a tree. The slanted lines join each parent to its children:
array: [13, 11, 12, 5, 6, 7]
13 index 0 (root)
/ \
11 12 index 1 and 2
/ \ /
5 6 7 index 3, 4, 5
Guess first: is this max-heap sorted? No. This array is a max-heap: 13 is above 11 and 12, 11 is above 5 and 6, and 12 is above 7. But 11 still comes before 12. A heap only promises that its root is the largest.
Heap sort runs in two phases: phase 1 builds a max-heap, then phase 2 keeps swapping the root to the back and fixing the heap that is left. Here's what happens to [12, 11, 13, 5, 6, 7]:
| Step | Heap | Already in place |
|---|---|---|
| Start | [12, 11, 13, 5, 6, 7] |
|
| Phase 1: build the max-heap | [13, 11, 12, 5, 6, 7] |
|
| Swap 13 to the end, fix the heap | [12, 11, 7, 5, 6] |
[13] |
| Swap 12 to the end, fix the heap | [11, 6, 7, 5] |
[12, 13] |
| Swap 11 to the end, fix the heap | [7, 6, 5] |
[11, 12, 13] |
| Repeat until the heap is empty | [5, 6, 7, 11, 12, 13] |
Here is the code, with a helper function, heapify:
function heapSort(arr) {
const n = arr.length;
// phase 1: build the max-heap, starting from the last parent
for (let i = Math.floor(n / 2) - 1; i >= 0; i--) heapify(arr, n, i);
// phase 2: swap the root (largest) to the end, the heap shrinks by one
for (let i = n - 1; i > 0; i--) {
[arr[0], arr[i]] = [arr[i], arr[0]];
heapify(arr, i, 0);
}
return arr;
}
function heapify(arr, size, root) {
let largest = root;
const left = 2 * root + 1;
const right = 2 * root + 2;
if (left < size && arr[left] > arr[largest]) largest = left;
if (right < size && arr[right] > arr[largest]) largest = right;
if (largest !== root) {
[arr[root], arr[largest]] = [arr[largest], arr[root]];
heapify(arr, size, largest); // keep sinking until it's fine
}
}
console.log(heapSort([12, 11, 13, 5, 6, 7]));
// [5, 6, 7, 11, 12, 13]
heapify(arr, size, root)fixes one node (one number in the tree). Hererootis the index of the number being fixed, not always the top of the tree. That number is compared with its two children. If a child is larger, the number is swapped with the larger child, thenheapifycontinues down from the number's new position (recursion).sizeis where the heap ends. Numbers from indexsizeonward are already in place and aren't touched again.- Phase 1 calls
heapifyfrom the last parent,Math.floor(n / 2) - 1, back down to index 0. The numbers after the last parent have no children, so they don't need fixing. - Phase 2: the root is always the largest, so it's swapped to the end. The heap shrinks by one, then
heapify(arr, i, 0)brings the next largest up to the root. [a, b] = [b, a]is a short way to swap two values.
Fast and frugal, but rarely used
- The tree is only log n levels tall (one level is one row). 1,000 numbers need only about 10 levels. Each time the root is taken, heapify sinks at most the height of the tree, and that happens n times. In Big-O, the total is O(n log n) in every case: best case, average case and worst case.
- It all happens inside the same array, with no extra array: its extra memory is O(1), the same however much data there is.
- Heap sort is not stable: the original order of equal values can change.
Why is heap sort rarely used? heapify jumps to indexes 2i + 1 and 2i + 2, which sit far apart. A CPU has a cache, a small, very fast memory. The cache loads data that sits close together all at once. Data that sits far away isn't in the cache yet, so the CPU has to fetch it from slower memory. That is called a cache miss. Quick sort and merge sort read their data in order, so in practice they're usually faster, even with the same Big-O.
⚠️ A heap of the wrong kind, at the wrong index, or that never shrinks
- A min-heap for ascending order. A min-heap is the opposite of a max-heap: its root is the smallest. Heap sort moves the root to the back first, so smallest-to-largest needs a max-heap. A min-heap gives descending order.
- Wrong child indexes. Because indexes start at 0, the children of
iare at2 * i + 1and2 * i + 2, not2 * i. - A
sizethat doesn't shrink. In phase 2,heapifymust usei, notn. Withn, numbers that are already in place get pulled back into the heap.
TL;DR: A max-heap is an array read as a tree: the children of index i are at 2i + 1 and 2i + 2. Every parent (a number that has children) is larger than or equal to its children, so the root (the top of the tree, index 0) is always the largest. Heap sort builds a max-heap, then keeps swapping the root to the back and fixing the shrinking heap. Heap sort is always O(n log n), uses O(1) extra memory, and isn't stable: the original order of equal values can change. It's rarely used, because its jumps between far-apart indexes often need data that isn't in the CPU cache (a small, very fast memory) yet.
⚡ Max-heap: the root is always the largest
Guess first: in a max-heap, the number at index i is larger than or equal to its two children, at index 2i + 1 and 2i + 2. [13, 11, 12, 5, 6, 7] is a max-heap. Is this array sorted?
No. Every number is larger than its children, but 11 still comes before 12. A heap only promises that its root (index 0) is the largest.
Meaning: A max-heap is an array read as a tree: the children of index i sit at 2i + 1 and 2i + 2, and every parent (a number that has children) is larger than or equal to its children. So the largest number is at the root, index 0.
⚡ Heap sort's two phases
Write:
function heapSort(arr) {
const n = arr.length;
// phase 1: build the max-heap, starting from the last parent
for (let i = Math.floor(n / 2) - 1; i >= 0; i--) heapify(arr, n, i);
// phase 2: swap the root (largest) to the end, the heap shrinks by one
for (let i = n - 1; i > 0; i--) {
[arr[0], arr[i]] = [arr[i], arr[0]];
heapify(arr, i, 0);
}
return arr;
}
Meaning: Phase 1 builds a max-heap. Phase 2 keeps swapping the root (the largest number) to the back, and the heap shrinks by one. heapify (a helper function) compares one parent with its two children, swaps if a child is larger, then keeps sinking. In phase 2, heapify uses i, not n, so numbers already in place aren't pulled back in.
⚡ Always O(n log n), but rarely used
Meaning: The heap's tree is only log n levels (rows) tall, and the root is taken n times. So heap sort is O(n log n) in every case, with O(1) extra memory. In practice heap sort is rarely used. Its jumps to far-apart indexes 2i + 1 and 2i + 2 often need data that isn't in the CPU cache (a small, very fast memory) yet.