23. Heap Sort
Build a max-heap in place, then repeatedly swap the max to the end and shrink the heap. O(n log n) in all cases with O(1) extra memory, but not stable.
How it works
Phase 1 builds a max-heap by sifting down every non-leaf node from the last one up to the root; this takes O(n). Phase 2 repeats: swap the root (the maximum) with the last item of the heap, shrink the heap by one, and sift the new root down. The sorted part grows from the right.
Diagram
flowchart TD
s0["start: heap 5 2 9 1 6 3 / sorted none"]
s1["build: heap 5 2 9 1 6 3 / sorted none"]
s2["build: heap 5 6 9 1 2 3 / sorted none"]
s3["build: heap 9 6 5 1 2 3 / sorted none"]
s4["extract: heap 6 3 5 1 2 / sorted 9"]
s5["extract: heap 5 3 2 1 / sorted 6 9"]
s6["extract: heap 3 1 2 / sorted 5 6 9"]
s7["extract: heap 2 1 / sorted 3 5 6 9"]
s8["extract: heap 1 / sorted 2 3 5 6 9"]
s0 -->|"sift down index 2"| s1
s1 -->|"sift down index 1"| s2
s2 -->|"sift down index 0"| s3
s3 -->|"swap max 9 to index 5"| s4
s4 -->|"swap max 6 to index 4"| s5
s5 -->|"swap max 5 to index 3"| s6
s6 -->|"swap max 3 to index 2"| s7
s7 -->|"swap max 2 to index 1"| s8
Step-by-step trace
Input: Sort [5, 2, 9, 1, 6, 3].
| Phase | Action | Heap part | Sorted part |
|---|---|---|---|
| start | - | [5, 2, 9, 1, 6, 3] | [] |
| build | sift down index 2 | [5, 2, 9, 1, 6, 3] | [] |
| build | sift down index 1 | [5, 6, 9, 1, 2, 3] | [] |
| build | sift down index 0 | [9, 6, 5, 1, 2, 3] | [] |
| extract | swap max 9 to index 5, sift down | [6, 3, 5, 1, 2] | [9] |
| extract | swap max 6 to index 4, sift down | [5, 3, 2, 1] | [6, 9] |
| extract | swap max 5 to index 3, sift down | [3, 1, 2] | [5, 6, 9] |
| extract | swap max 3 to index 2, sift down | [2, 1] | [3, 5, 6, 9] |
| extract | swap max 2 to index 1, sift down | [1] | [2, 3, 5, 6, 9] |
Result: Sorted: [1, 2, 3, 5, 6, 9].
Complexity
| Operation | Time | Space |
|---|---|---|
| All cases | O(n log n) | O(1) |
| Build heap phase | O(n) | O(1) |
| Stable? | no | - |
Python reference implementation
def heap_sort(a):
a = list(a)
n = len(a)
for i in range(n // 2 - 1, -1, -1): # build a max-heap bottom up
_sift_down_max(a, i, n)
for end in range(n - 1, 0, -1):
a[0], a[end] = a[end], a[0] # move the max to its final place
_sift_down_max(a, 0, end)
return a
def _sift_down_max(a, i, n):
while True:
left, right, largest = 2 * i + 1, 2 * i + 2, i
if left < n and a[left] > a[largest]:
largest = left
if right < n and a[right] > a[largest]:
largest = right
if largest == i:
return
a[i], a[largest] = a[largest], a[i]
i = largest
Common mistakes and tips
- Children of
iare2i + 1and2i + 2; the last non-leaf isn // 2 - 1. - Sift down only within the current heap size, not the whole array.
The trace above is generated by running the code in dsa/ with python3 tools/build.py, and checked by the tests in tests/.
| Previous: Quick Sort | Next: Binary Search |