Sub topic 7
Tracing Heap Sort Step by Step
This chapter assumes you already know the sift_down, build_max_heap, and heap_sort functions from the earlier chapters, and the index formulas left(i) = 2i + 1 and right(i) = 2i + 2. We will run heap sort by hand on [5, 2, 9, 1, 7, 3] and check each step against instrumented code.
Phase 1: Building the Max-Heap
The array has n = 6 elements, so the last non-leaf node is at index n // 2 - 1 = 2. Build-heap calls sift-down on indices 2, 1, and 0, in that order.
| Step | Node (index: value) | Children compared | Action | Array after |
|---|---|---|---|---|
| start = 2 | 2: 9 | 5: 3 | 9 ≥ 3, no swap | `[5, 2, 9, 1, 7, 3]` |
| start = 1 | 1: 2 | 3: 1, 4: 7 | swap 2 with 7 | `[5, 7, 9, 1, 2, 3]` |
| start = 0 | 0: 5 | 1: 7, 2: 9 | swap 5 with 9, then compare 5 with child 3 at index 5: no swap | `[9, 7, 5, 1, 2, 3]` |
The root step shows why sift-down needs a loop. After 5 moves down to index 2, it still has to be compared with its own child. Here 5 ≥ 3, so it stops.
Phase 2: Swap, Shrink, Sift
Each pass swaps the root (the current maximum) with a[end]. That position is then final. The pass ends by sifting the new root down within a[0:end].
- end = 5: Swap 9 and 3 to get
[3, 7, 5, 1, 2 | 9]. The 3 is smaller than its larger child 7, so they swap. At index 1, 3 is compared with children 1 and 2, and 3 ≥ 2, so it stops. Heap:[7, 3, 5, 1, 2]. - end = 4: Swap 7 and 2 to get
[2, 3, 5, 1 | 7, 9]. The 2 swaps with 5. Index 2 has no children inside the heap. Heap:[5, 3, 2, 1]. - end = 3: Swap 5 and 1 to get
[1, 3, 2 | 5, 7, 9]. The 1 swaps with 3. Index 1's child would be index 3, which is outside the heap. Heap:[3, 1, 2]. - end = 2: Swap 3 and 2 to get
[2, 1 | 3, 5, 7, 9]. 2 ≥ 1, so there is no swap. - end = 1: Swap 2 and 1 to get
[1 | 2, 3, 5, 7, 9]. A one-element heap needs no work.
Result: [1, 2, 3, 5, 7, 9].
Checking the Trace with Code
The version below prints the array after every sift-down so you can compare it with your hand trace.
def sift_down(a, start, 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 heap_sort_traced(a):
n = len(a)
for start in range(n // 2 - 1, -1, -1):
sift_down(a, start, n)
print(f"build start={start}: {a}")
for end in range(n - 1, 0, -1):
a[0], a[end] = a[end], a[0]
sift_down(a, 0, end)
print(f"sort end={end}: heap={a[:end]} sorted={a[end:]}")
data = [5, 2, 9, 1, 7, 3]
heap_sort_traced(data)
print(data)Expected output:
build start=2: [5, 2, 9, 1, 7, 3]
build start=1: [5, 7, 9, 1, 2, 3]
build start=0: [9, 7, 5, 1, 2, 3]
sort end=5: heap=[7, 3, 5, 1, 2] sorted=[9]
sort end=4: heap=[5, 3, 2, 1] sorted=[7, 9]
sort end=3: heap=[3, 1, 2] sorted=[5, 7, 9]
sort end=2: heap=[2, 1] sorted=[3, 5, 7, 9]
sort end=1: heap=[1] sorted=[2, 3, 5, 7, 9]
[1, 2, 3, 5, 7, 9]At every line the sorted suffix grows by one, and each element in it is at least as large as every element still in the heap. That invariant is why the algorithm is correct.
Exercise
Run the build phase on [4, 10, 3, 5, 1] by hand. What is the max-heap, and what does the array look like after the first swap-and-sift pass (end = 4)?
Show answer
The build phase sifts index 1 first. 10 is at least as large as its children 5 and 1, so nothing moves. Then it sifts index 0: 4 swaps with 10, then with 5, giving the heap [10, 5, 3, 4, 1]. For end = 4, swapping 10 and 1 gives [1, 5, 3, 4 | 10]. The 1 swaps with 5, then with 4 at index 3. Index 4 is excluded because end = 4. The result is [5, 4, 3, 1, 10].
Exercise
In the main trace, how many element swaps does sift-down perform in total across both phases, not counting the root-to-end swaps?
Show answer
Six. The build phase does three (2↔7, 5↔9, and none at start=2 or after 5 settles, so 2↔7 and 5↔9 make two). The sort phase does 3↔7, 2↔5, and 1↔3, which is three more. Recounting: the build phase has 2 swaps and the sort phase has 3 swaps, for a total of 5.