Heap sort turns the array into a max-heap (a complete binary tree stored in the array itself, with every parent at least as large as its children), then repeatedly swaps the maximum at the root to the end and repairs the heap. It guarantees O(n log n) time in every case with only O(1) extra memory, a combination neither merge sort nor quick sort offers. It is not stable and has poor cache behavior, so in practice it shines as a safety net (introsort's fallback) and as the engine behind top-k and partial sorting.
Think of it like
A knockout tournament with a hall of fame
Run a tournament bracket and the champion rises to the top. Retire the champion to the hall of fame (the end of the array) and let a newcomer take the empty top seat. Only the matches along one path from the top down need to be replayed to crown the next champion, about log₂ n of them, not a whole new tournament.
Heaps in one minute
A binary heap is a complete binary tree laid out level by level in an array, so no pointers are needed: the tree shape is implied by the indices. In a max-heap every parent is greater than or equal to its children, so the maximum is always at index 0. See Heaps & Priority Queues for the full data structure.
| Relation (0-based) | Formula | Example for i = 4 |
|---|---|---|
| Left child | 2i + 1 | 9 |
| Right child | 2i + 2 | 10 |
| Parent | ⌊(i − 1) / 2⌋ | 1 |
| Last internal node | ⌊n/2⌋ − 1 | for n = 10: index 4 |
| Leaves | indices ⌊n/2⌋ .. n − 1 | for n = 10: indices 5 to 9 |
How it works
- 1
Build a max-heap
Sift down every internal node, from the last one (
⌊n/2⌋ − 1) back to the root. Afterwardsa[0]is the maximum. - 2
Move the max to the end
Swap
a[0]witha[end]. The largest element is now in its final position, just past the heap. - 3
Shrink and repair
The heap is now
a[0..end-1]. The new root may be too small, so sift it down to restore the heap property. - 4
Repeat
Decrease
endand repeat until the heap has one element. The array is sorted in ascending order.
Sift down
Sift down repairs a heap whose only violation is at node i. Compare a[i] with its children; if a child is larger, swap with the larger child (so the new parent dominates both subtrees) and continue from that child's position. Stop when a[i] is at least as large as both children, or when it becomes a leaf. Each step goes down one level, so it costs O(log n).
Worked example
| Step | Array | What happened |
|---|---|---|
| Start | [4, 10, 3, 5, 1] | n = 5, last internal node is index 1 |
| Sift down i = 1 | [4, 10, 3, 5, 1] | 10 is larger than its children 5 and 1: no change |
| Sift down i = 0 | [10, 5, 3, 4, 1] | 4 swaps with 10, then with 5. Max-heap built |
| Extract 10 | [5, 4, 3, 1 | 10] | Swap root with a[4], sift 1 down past 5 and 4 |
| Extract 5 | [4, 1, 3 | 5, 10] | Swap root with a[3], sift 1 down past 4 |
| Extract 4 | [3, 1 | 4, 5, 10] | Swap root with a[2]; 3 is larger than its child 1 |
| Extract 3 | [1 | 3, 4, 5, 10] | Swap root with a[1]. One element left: done |
| separates the heap from the sorted suffix. Result: [1, 3, 4, 5, 10].Why build-heap is O(n), not O(n log n)
Building the heap calls sift down about n/2 times, so O(n log n) is an easy upper bound, but it is not tight. Sift down from a node costs at most its height, and most nodes are near the bottom: half are leaves (height 0, no work), a quarter have height 1, an eighth height 2, and so on.
Complexity analysis
Phase 2 performs n − 1 extractions, each followed by a sift down of up to ⌊log₂ n⌋ levels with two comparisons per level, so the whole sort is O(n log n) and uses roughly 2n log₂ n comparisons in the worst case. Unlike quick sort, there is no bad input: the shape of a heap depends only on n, not on the values.
Guaranteed
- O(n log n) worst case, no pathological inputs
- O(1) extra memory and no recursion
- Predictable running time for real-time systems
Not adaptive
- Sorted input still costs Θ(n log n) with distinct keys
- Building the heap scrambles any existing order
- Only all-equal keys are fast (sift down stops at once)
Why it is unstable
Swapping the root to the end moves elements across the whole array, ignoring the order of equal keys. Take [5a, 5b, 3]: it is already a valid max-heap (5a is not smaller than its children). Extracting the root swaps 5a to the end, giving [3, 5b | 5a]; repairing and extracting again gives [3 | 5b, 5a]. The equal keys come out reversed.
Heap sort vs quick sort in practice
Both are in-place O(n log n) sorts on average, yet quick sort is usually noticeably faster. The difference is the memory access pattern. Partitioning scans the array sequentially, so the CPU prefetcher keeps data flowing from cache. Sift down jumps from i to 2i + 1: once the heap is larger than the cache, nearly every level touches a new cache line far away from the previous one.
| Heap sort | Quick sort | |
|---|---|---|
| Worst case | O(n log n) | O(n²) (unless introsort) |
| Comparisons (typical) | about 2n log₂ n | about 1.39 n log₂ n |
| Memory access | Scattered jumps between levels | Sequential scans |
| Branch prediction | Poor: which child is larger is a coin flip | Better, especially with branchless partitioning |
| Extra space | O(1) | O(log n) stack |
| Stable | No | No |
Partial sorting and top-k
Heap sort produces its output from largest to smallest, so it can stop early. After an O(n) build, extracting just the k largest elements costs O(k log n), for a total of O(n + k log n). When the data is a stream or too large to modify, keep a min-heap of size k instead: each new element that beats the heap's minimum replaces it, for O(n log k) time and O(k) memory.
| Approach | Time | Extra space | Notes |
|---|---|---|---|
| Full sort, take k | O(n log n) | depends on sort | Simplest; wasteful when k is small |
| Build heap + k extractions | O(n + k log n) | O(1) | In place; returns the top k in order |
| Size-k min-heap | O(n log k) | O(k) | Works on streams; Python's heapq.nlargest |
| Quickselect | O(n) expected | O(1) | Top k unordered; see Quick Sort |
std::partial_sort uses the heap approach: it keeps a heap of the k best candidates while scanning, then sorts that heap.Heap sort's real job: introsort's safety net
Few libraries use heap sort as their main sort, but many rely on it. Introsort (C++ std::sort, .NET Array.Sort) runs quick sort and switches to heap sort when the recursion depth exceeds about 2 log₂ n, guaranteeing O(n log n) without extra memory. Heap sort is also popular in kernels and embedded or real-time systems, where a predictable worst case, no recursion and no allocation matter more than average speed.
Complexity
| Case | Time | Space | Notes |
|---|---|---|---|
| Build heap | O(n) | O(1) | Bottom-up sift down (Floyd) |
| Best | O(n log n) | O(1) | With distinct keys; O(n) only when all keys are equal |
| Average | O(n log n) | O(1) | About 2n log₂ n comparisons for the classic version |
| Worst | O(n log n) | O(1) | No pathological inputs |
| Top-k (in place) | O(n + k log n) | O(1) | Build, then k extractions |
| Top-k (streaming) | O(n log k) | O(k) | Min-heap of size k |
In-place, not stable, not adaptive.
Implementation
Bottom-up heap construction followed by repeated extraction of the maximum, with an iterative sift down.
def heap_sort(a: list[int]) -> list[int]:
n = len(a)
for i in range(n // 2 - 1, -1, -1): # phase 1: build a max-heap in O(n)
sift_down(a, i, n)
for end in range(n - 1, 0, -1): # phase 2: sort down
a[0], a[end] = a[end], a[0] # move the max just past the heap
sift_down(a, 0, end) # repair the heap a[0:end]
return a
def sift_down(a: list[int], i: int, size: int) -> None:
while True:
largest = i
left, right = 2 * i + 1, 2 * i + 2
if left < size and a[left] > a[largest]:
largest = left
if right < size and a[right] > a[largest]:
largest = right
if largest == i:
return # heap property holds here
a[i], a[largest] = a[largest], a[i]
i = largestKey takeaways
- Heap sort builds a max-heap in the array, then repeatedly swaps the root to the end and sifts the new root down.
- Building the heap bottom-up is O(n); the n − 1 extractions cost O(log n) each, so the sort is O(n log n) in every case.
- It uses O(1) extra space and no recursion, but it is not stable and not adaptive.
- Scattered memory access makes it slower than quick sort in practice, which is why it mostly serves as introsort's worst-case fallback.
- The same machinery gives top-k in O(n + k log n) in place, or O(n log k) on a stream with a size-k min-heap.
Common pitfalls
- Building the heap by inserting elements one at a time with sift up (O(n log n)) instead of sifting down from the last internal node
⌊n/2⌋ − 1to the root (O(n)). - Sifting down within the full array length instead of the current heap size, which pulls already-sorted elements back into the heap.
- Swapping with the first larger child instead of the largest child, which can leave the heap property broken.
- Using a max-heap of all n elements for streaming top-k; a size-k min-heap uses far less memory and is faster.
Interview tips
- Be ready to prove build-heap is O(n) with the height-sum argument; it is a classic follow-up question.
- Know the 0-based index formulas cold: children at
2i + 1and2i + 2, parent at⌊(i − 1)/2⌋. - For "k largest" or "k closest" questions, propose a size-k heap (O(n log k)) and compare it with quickselect (O(n) expected).
Real-world applications
- Worst-case fallback inside introsort (C++
std::sort, .NETArray.Sort). - Kernels, embedded and real-time systems that need guaranteed time with no recursion or allocation.
- Partial sorting and top-k queries (
std::partial_sort,heapq.nlargest). - Priority scheduling and event simulation, where the heap itself is the main data structure.
Practice problems
Test yourself
What is the time complexity of building a max-heap from an unordered array with bottom-up sift down?
Related topics
Finished this lesson? Track it to see your progress on the roadmap.