Heap sort
medium 18 minHeap sort turns the array into a max-heap in O(n), then repeatedly swaps the root (the maximum) to the end and sifts the new root down in O(log n).
Video lesson · Chapter 1 of 6
Who gets the final slot?
Heapsort — The heaviest gem goes last
1:26Reel
Read caption
Lux uses the same five gem slots as a max-heap and an expanding sorted suffix. Crown the maximum. Park it. Repair the heap.
How it works
Step through the idea, or press Play.
Build a max-heap. Sift down every parent, from the last one back to the root, so the largest value ends up at index 0
Understand it
Start here
What heap sort is
Heap sort is a comparison sort built on a binary max-heap. It first rearranges the array so that the largest value sits at the front, then repeatedly moves that maximum to the back of the array and repairs the heap for the values that are left. Think of a tournament: the winner takes the last open place, a short replay crowns the next winner, and so on until every place is filled.
Heapify
Turn the whole array into a max-heap, bottom up, in .
Extract
The root is the maximum. Swap it with the last heap slot.
Adjust
Sift the new root down to restore the heap in .
Place
The swapped-out maximum is in its final slot. The sorted part grows by one.
Foundations
A max-heap lives inside the array
A binary max-heap is a complete binary tree in which every parent is greater than or equal to its children, so the root is the maximum. Because the tree is complete, it packs into an array level by level with no gaps and no pointers. See heap properties for the full story.
Index arithmetic (0-based)
The heap [10, 5, 3, 4, 1]
| Index | Value | Parent | Left child | Right child |
|---|---|---|---|---|
| 0 | 10 (root) | none | : 5 | : 3 |
| 1 | 5 | : 10 | : 4 | : 1 |
| 2 | 3 | 0: 10 | 5: out of range | 6: out of range |
| 3 | 4 | : 5 | leaf | leaf |
| 4 | 1 | : 5 | leaf | leaf |
Core routine
Sift down (heapify)
heapify(arr, n, i): sink arr[i] to its place
def heapify(arr, n, i): """Sift arr[i] down inside the heap arr[0..n-1].""" largest = i left, right = 2 * i + 1, 2 * i + 2 if left < n and arr[left] > arr[largest]: largest = left if right < n and arr[right] > arr[largest]: largest = right if largest != i: arr[i], arr[largest] = arr[largest], arr[i] heapify(arr, n, largest)a = [4, 10, 3, 5, 1]heapify(a, 5, 1) # 10 already beats 5 and 1: no changeheapify(a, 5, 0) # 4 sinks: swap with 10, then with 5print(a) # [10, 5, 3, 4, 1]Phase 1
Build the max-heap bottom up
Leaves are already one-node heaps. So start at the last parent and heapify each node, moving left to the root. When a node is processed, both of its subtrees are heaps already, which is exactly what heapify needs.
build_max_heap
Worked example: [4, 10, 3, 5, 1]
- 1
Start
, last parent . Slots 2, 3 and 4 are leaves. As a tree: root 4, children 10 and 3, then 5 and 1 under 10.
- 2
i = 1 (value 10)
Children 5 and 1. and : already a heap, no swap.
- 3
i = 0 (value 4)
Children 10 and 3. : swap, giving
[10, 4, 3, 5, 1]. - 4
Follow 4 to slot 1
Children 5 and 1. : swap, giving
[10, 5, 3, 4, 1]. Slot 3 is a leaf, so stop. - 5
Done
Max-heap
[10, 5, 3, 4, 1]after 6 comparisons and 2 swaps.
Deep dive
Why building the heap is O(n)
Each heapify costs at most the height of its node, and at most nodes have height . Half the nodes are leaves (height 0), a quarter have height 1, and only the root has height . Expensive nodes are rare.
Total work of build-heap
The series that converges
| n | Most swaps, bottom-up build | Inserting one by one (sift up) | |
|---|---|---|---|
| 7 | 4 | 10 | about 20 |
| 15 | 11 | 34 | about 59 |
| 1,023 | 1,013 | 8,194 | about 10,229 |
| 1,000,000 | 999,993 | about 18 million | about 19.9 million |
Phase 2
Extract the max, n - 1 times
Now arr[0] is the largest value. Swap it with the last slot of the heap: the maximum lands in its final position. Shrink the heap by one, so that slot is never touched again, and sift the new root down. The heap shrinks from the right while the sorted part grows from the right.
| Extraction | Swap | After sifting the root down | Heap | sorted |
|---|---|---|---|
| start | 10, 5, 3, 4, 1 | | ||
| 1 | 10 ↔ 1 | 1 sinks below 5, then below 4 | 5, 4, 3, 1 | 10 |
| 2 | 5 ↔ 1 | 1 sinks below 4 | 4, 1, 3 | 5, 10 |
| 3 | 4 ↔ 3 | 3 already beats 1 | 3, 1 | 4, 5, 10 |
| 4 | 3 ↔ 1 | heap of one | 1 | 3, 4, 5, 10 |
The full algorithm
end, not n, so the sorted suffix stays out of the heap.Put together
The complete algorithm
def heapify(arr, n, i): largest = i left, right = 2 * i + 1, 2 * i + 2 if left < n and arr[left] > arr[largest]: largest = left if right < n and arr[right] > arr[largest]: largest = right if largest != i: arr[i], arr[largest] = arr[largest], arr[i] heapify(arr, n, largest)def heap_sort(arr): n = len(arr) for i in range(n // 2 - 1, -1, -1): # phase 1: build heapify(arr, n, i) for end in range(n - 1, 0, -1): # phase 2: extract arr[0], arr[end] = arr[end], arr[0] heapify(arr, end, 0) return arrprint(heap_sort([4, 10, 3, 5, 1])) # [1, 3, 4, 5, 10]print(heap_sort([12, 11, 13, 5, 6, 7])) # [5, 6, 7, 11, 12, 13]- 1HeapifyBuild the max-heap once
- 2ExtractTake the root, the maximum
- 3AdjustSift the new root down
- 4PlaceMax sits at the end; repeat
Heapify happens once; Extract, Adjust and Place loop $n - 1$ times.
Complexity
O(n log n) in every case
Total time
| Case | Time | Why |
|---|---|---|
| Best | Each extraction brings a small leaf value to the root, and it usually sinks most of the way back down | |
| Average | Same work for any order of distinct values | |
| Worst | No bad pivot, no bad input: the heap is always balanced | |
| Space | extra | Only swaps inside the array; iterative heapify needs no stack |
Properties
In place, not stable, not adaptive
In place
extra memory. The heap and the sorted part share the one array.
Not stable
Long-distance swaps can jump an equal value over its twin, so equal keys may change order.
Not adaptive
Sorted, reversed and random inputs all cost about the same. Nearly sorted data gets no discount.
Comparison based
Only compares values, so the lower bound applies. Heap sort meets it.
def heap_sort_by_key(arr): n = len(arr) def heapify(size, i): largest, l, r = i, 2 * i + 1, 2 * i + 2 if l < size and arr[l][0] > arr[largest][0]: largest = l if r < size and arr[r][0] > arr[largest][0]: largest = r if largest != i: arr[i], arr[largest] = arr[largest], arr[i] heapify(size, largest) for i in range(n // 2 - 1, -1, -1): heapify(n, i) for end in range(n - 1, 0, -1): arr[0], arr[end] = arr[end], arr[0] heapify(end, 0) return arrprint(heap_sort_by_key([(3, "a"), (3, "b"), (1, "c")]))# [(1, 'c'), (3, 'b'), (3, 'a')]: 3a started first but ends lastHead to head
Heap sort vs quick sort vs merge sort
| Property | Heap sort | Quick sort | Merge sort |
|---|---|---|---|
| Best time | |||
| Worst time | |||
| Extra space | stack | ||
| Stable | No | No | Yes |
| In place | Yes | Yes | No |
| Cache behaviour | Poor: jumps from to | Excellent: sequential scans | Good: sequential merges |
| In practice | Safety net, top-k | Fastest on average | Stable sorts, linked lists, external data |
Which O(n log n) sort?
In practice
Where heap sort is used
Introsort: quick sort with a heap sort safety net
std::sort and .NET's Array.Sort work this way: quick sort's speed, heap sort's worst-case guarantee, insertion sort for tiny ranges.Good for
- A guaranteed with no bad inputs.
- Memory-constrained code: extra space.
- Finding the largest or smallest values: build once, extract times.
- Real-time and embedded systems where the worst case matters.
- Learning priority queues: the same heapify and sift-down routines.
Avoid when
- Stability is required: use merge sort or Timsort.
- Data is nearly sorted: insertion sort or Timsort is much faster.
- Cache performance is critical on large arrays.
- Average-case speed matters most: quick sort is usually faster.
Top k
Stop after extractions: , or keep a size- min-heap for on a stream.
k-sorted data
Each value is at most slots from home: a min-heap of size sorts it in .
Merging k lists
A heap of the list heads picks the next smallest in .
Recap
Key takeaways
Key points
- Heap sort has two phases: build a max-heap bottom up, then times swap the root to the end and sift down.
- In a 0-based array: children at and , parent at , last parent at .
- Build-heap is because ; the comes from the extractions.
- best, average and worst for distinct values; extra space.
- Not stable and not adaptive; slower than quick sort in practice because of poor cache locality.
- Used as introsort's fallback and for top-k problems.