This lesson builds on Heaps and priority queues: the array-as-tree layout, sift down and bottom-up heapify are used here without re-deriving them.
Mental model
Pop from a priority queue n times and the values come out sorted. Heap sort does exactly that, but without a second array: the heap and the output share one array.
- The heap occupies the front,
items[0..heapSize). - The sorted output occupies the back,
items[heapSize..n), and grows leftwards.
Each step removes the heap's root and puts it into the slot the shrinking heap just gave up. For ascending order the root must be the largest remaining value, so heap sort uses a max-heap: every parent is greater than or equal to its children.
The two phases
build: for i = n/2 − 1 down to 0: siftDown(i, n) (max-heap over the whole array)
extract: for end = n − 1 down to 1:
swap items[0], items[end] (the maximum goes to its final slot)
siftDown(0, end) (restore the heap in items[0..end))
siftDown(i, size) compares the two children of i that lie inside the heap, takes the larger
(the left one on ties), and swaps if that child is larger than items[i]; it repeats from the child
and stops at a leaf or when the parent is not smaller. Elements at size and beyond are invisible
to it, which is how the sorted tail stays untouched.
A small example
Sort 4 10 3 5 1.
Build. n = 5, so the parents are indices 1 and 0. Index 1 (10) is already larger than its
children 5 and 1. Index 0 (4): the larger child is 10, swap → 10 4 3 5 1; continue at index 1:
the larger child is 5, swap → 10 5 3 4 1. That is a max-heap.
Extract.
| Step | Swap root with | Array after the swap | After sift down |
|---|---|---|---|
| end = 4 | 1 | 1 5 3 4 │ 10 |
5 4 3 1 │ 10 |
| end = 3 | 1 | 1 4 3 │ 5 10 |
4 1 3 │ 5 10 |
| end = 2 | 3 | 3 1 │ 4 5 10 |
3 1 │ 4 5 10 |
| end = 1 | 1 | 1 │ 3 4 5 10 |
done |
The bar separates the heap from the sorted tail. In the lab the tree above the array shows only the heap part; slots of the tail turn green and leave the tree.
Cost
- Build: O(n), by the same height argument as heapify in the previous lesson.
- Extract: n − 1 sift downs on heaps of size n − 1, n − 2, …, 1. Each costs at most ⌊log₂ size⌋ levels with two comparisons per level, so the phase is O(n log n), and for most inputs most sifts go nearly to the bottom, so it is also Ω(n log n).
- Total: Θ(n log n) comparisons in the best, average and worst case, about 2n log₂ n in the worst case for this standard version.
- Space: O(1) extra. The sift down is a loop, not recursion, and no buffer is needed.
The Already sorted preset shows there is no shortcut: building the max-heap first moves the large values to the front, which scrambles the sorted input before extraction sorts it again.
Not stable
Run the Not stable preset: 5a 1 5b 2 5c. Building the heap leaves 5a 5c 5b 2 1, and the
extractions move the root to the end each time. The result is 1 2 5b 5c 5a: the three equal 5s
come out in a different order than they went in. The long root-to-end swap jumps elements over
equal ones, and nothing ever restores their original order.
How it compares
| Heap sort | Merge sort | Quicksort (tuned) | |
|---|---|---|---|
| Worst-case time | Θ(n log n) | Θ(n log n) | Θ(n²), avoided in practice by random or median pivots and introsort |
| Extra space | O(1) | O(n) | O(log n) stack |
| Stable | no | yes | no |
| Adaptive to sorted input | no | not this version (Timsort is) | depends on pivot |
| Memory access | jumps between i and 2i + 1: poor cache locality on large arrays | sequential | sequential |
Heap sort's guarantees are excellent and its constant factors are not. Each sift down jumps from index i to about 2i, so on large arrays nearly every step touches a different cache line, and it makes more comparisons than quicksort on average. That is why it is rarely the default sort, and exactly why it is the perfect fallback.
Where it runs
- Introsort (C++
std::sortin libstdc++ and libc++, C#Array.Sort): quicksort normally, but when the recursion depth passes a limit around 2 log₂ n, the current range is finished with heap sort. That caps the worst case at O(n log n) without giving up quicksort's average speed. - C++
std::partial_sort(the k smallest elements, sorted) is typically a heap of size k: O(n log k).std::make_heapfollowed bystd::sort_heapis a complete heap sort you can call directly. - Top-k problems in any language use the same idea with a priority queue (see the previous lesson's third practice question).
Variants worth knowing
- Bottom-up heap sort (Floyd's idea): during extraction, sift the hole all the way down by choosing the larger child without comparing against the moved element, then sift the element up from the bottom. Since the moved element usually belongs near the bottom anyway, this saves about half of the comparisons.
- d-ary heaps (more than two children per node) make the tree shallower; .NET's
PriorityQueueuses four children per node.
The teaching implementation
HeapSort.Sort / heap_sort takes a comparison (or a key in Python) and sorts ascending with the
rules above: the larger child, the left one on ties, and a swap only when the child is strictly
larger. Because heap sort is unstable, the shared fixture records the exact order this
implementation leaves equal keys in (4a 4b 4c 4d becomes 4b 4c 4d 4a), and all four languages
must reproduce it; each is also compared with its built-in sort on 500 random inputs.
Common mistakes
- Using a min-heap for ascending order in place. The minimum would have to go to the front, which is where the heap lives. Use a max-heap (or sort descending with a min-heap).
- Sifting down over the whole array instead of
items[0..end): the sorted tail gets pulled back into the heap. - Building the heap top-down with n sift ups: correct, but O(n log n) for the build instead of O(n).
- Expecting stability because the output "looks" ordered on small examples.
Worked practice
1. After the build phase on 2 8 5 3 9 1, what is the array?
Answer
9 8 5 3 2 1. Index 2 (5) has one child, 1, and stays. Index 1 (8): children 3 and 9; 9 is larger
and larger than 8, swap → 2 9 5 3 8 1. Index 0 (2): children 9 and 5; swap with 9 →
9 2 5 3 8 1; continue at index 1: children 3 and 8; swap with 8 → 9 8 5 3 2 1.
2. How many root-to-end swaps does heap sort make on n elements?
Answer
Exactly n − 1, one per extraction (end = n − 1 down to 1). The last element left in the heap is the smallest and is already at index 0.
3. Why can heap sort guarantee O(n log n) when quicksort cannot?
Answer
Its work does not depend on lucky choices. The heap is always a complete tree of height ⌊log₂ n⌋, so every sift down is bounded by that height whatever the values are. Quicksort's recursion depth depends on where the pivots land, which can be anywhere.
Summary
- Build a max-heap in O(n); then n − 1 times, swap the root to the end of the heap and sift down.
- Θ(n log n) comparisons in every case, O(1) extra space, not stable.
- Poor cache locality makes it slower than quicksort on average, so libraries use it as introsort's worst-case fallback.