Sub topic 6
Heap Sort: Swap the Root, Shrink, Repeat
This chapter assumes you already know three things from earlier chapters. First, how a complete binary tree maps onto array indices. Second, what the max-heap property is. Third, how sift_down and build_max_heap work. Here we put those pieces together into the full sorting algorithm.
The core idea
A max-heap has one useful guarantee: the largest element is always at index 0. Heap sort uses that guarantee repeatedly.
- Turn the whole array into a max-heap.
- Swap the root (the maximum) with the last element of the heap. The maximum is now in its final sorted position.
- Shrink the heap by one, so the sorted element is no longer part of it.
- The new root probably breaks the heap property, so sift it down.
- Repeat until the heap holds one element.
The array is split into two regions. The front, a[0:end], is a max-heap. The back, a[end:], holds the largest elements in sorted order. Each pass moves the boundary one step left.
The implementation
The code below includes the helpers from earlier chapters so it runs on its own.
def sift_down(a, start, end):
# Restore the max-heap property for the subtree rooted at start,
# considering only a[0:end].
root = start
while True:
child = 2 * root + 1
if child >= end:
break
if child + 1 < end and a[child + 1] > a[child]:
child += 1
if a[root] >= a[child]:
break
a[root], a[child] = a[child], a[root]
root = child
def build_max_heap(a):
n = len(a)
for start in range(n // 2 - 1, -1, -1):
sift_down(a, start, n)
def heap_sort(a):
build_max_heap(a)
for end in range(len(a) - 1, 0, -1):
a[0], a[end] = a[end], a[0]
sift_down(a, 0, end)
data = [5, 2, 9, 1, 7, 3]
heap_sort(data)
print(data) # [1, 2, 3, 5, 7, 9]Why the `end` argument matters
sift_down receives end as an exclusive bound. After the swap, a[end] holds a sorted element, so the call sift_down(a, 0, end) must never look at it. If you passed len(a) instead, sift-down would treat the sorted tail as part of the heap and pull large values back toward the front.
Why the loop stops at 1
The loop runs end from n - 1 down to 1. Once only one element is left in the heap, it is the smallest value and already sits at index 0. A final swap of a[0] with itself would do nothing.
Common mistakes
| Mistake | Symptom |
|---|---|
| Sifting down with `len(a)` instead of `end` | Output is partially sorted or scrambled |
| Skipping `build_max_heap` | Root is not the maximum, so the order is wrong |
| Using a min-heap with this loop | Array ends up in descending order |
| Off-by-one in loop, e.g. `range(len(a), 0, -1)` | `IndexError` on the first swap |
Why this is in place
Every operation is a swap inside the original array. The heap and the sorted region share the same list, and no extra list is allocated. The extra memory is a few index variables, no matter how large the input is. The cost of these steps is analyzed in a later chapter.
Exercise
After buildmaxheap runs on [5, 2, 9, 1, 7, 3], the array is [9, 7, 5, 1, 2, 3]. What does the array look like after the first pass of the heap sort loop (one swap plus one sift-down)?
Show answer
Swapping a[0] and a[5] gives [3, 7, 5, 1, 2, 9]. Sifting down index 0 within a[0:5] swaps 3 with its larger child 7, giving [7, 3, 5, 1, 2, 9]. Then 3 is compared with its only child in range, 2 at index 4. 3 is larger, so sift-down stops. The result is [7, 3, 5, 1, 2, 9].
Exercise
A student writes siftdown(a, 0, len(a)) inside the loop instead of siftdown(a, 0, end). Why does this break the sort?
Show answer
The sift-down would include the sorted tail a[end:] in the heap. Large values that were already placed at the end could be swapped back toward the root, which undoes earlier passes.