Sub topic 7
Tracing Heap Sort Step by Step
This chapter runs heap sort by hand on one small array and records every swap. Once you have traced it yourself, the algorithm is easier to debug, and you can spot a broken implementation by its output.
The chapter assumes you have read the earlier chapters on index arithmetic (parent, left, right), the max-heap property, sift_down, build_max_heap, and heap_sort. It reuses those functions and only adds print statements.
The Input and the Plan
The example input is the same array used earlier in the tutorial:
data = [5, 2, 9, 1, 7, 3]Heap sort has two phases, and the trace follows them in order:
- Build phase. Call
sift_downon each non-leaf index, fromn // 2 - 1down to0. Forn = 6that means indices 2, 1, and 0. - Sort phase. For
endfrom 5 down to 1, swapa[0]witha[end], then callsift_down(a, 0, end)so the heap shrinks by one each round.
An Instrumented Heap Sort
Tracing by hand is easy to get wrong, so the version below prints each step. Its logic matches the earlier sift_down and heap_sort exactly. The only addition is a trace flag that reports each swap before it happens.
def sift_down(a, start, end, trace=False):
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
if trace:
print(f" swap {a[root]} (index {root}) with {a[child]} (index {child})")
a[root], a[child] = a[child], a[root]
root = child
def traced_heap_sort(a):
n = len(a)
print(f"input: {a}")
for start in range(n // 2 - 1, -1, -1):
print(f"sift_down(start={start}, end={n})")
sift_down(a, start, n, trace=True)
print(f" -> {a}")
print(f"max-heap: {a}")
for end in range(n - 1, 0, -1):
a[0], a[end] = a[end], a[0]
print(f"swap root into index {end}: {a}")
sift_down(a, 0, end, trace=True)
print(f" heap {a[:end]} | sorted {a[end:]}")
print(f"result: {a}")
traced_heap_sort([5, 2, 9, 1, 7, 3])Running it prints:
input: [5, 2, 9, 1, 7, 3]
sift_down(start=2, end=6)
-> [5, 2, 9, 1, 7, 3]
sift_down(start=1, end=6)
swap 2 (index 1) with 7 (index 4)
-> [5, 7, 9, 1, 2, 3]
sift_down(start=0, end=6)
swap 5 (index 0) with 9 (index 2)
-> [9, 7, 5, 1, 2, 3]
max-heap: [9, 7, 5, 1, 2, 3]
swap root into index 5: [3, 7, 5, 1, 2, 9]
swap 3 (index 0) with 7 (index 1)
heap [7, 3, 5, 1, 2] | sorted [9]
swap root into index 4: [2, 3, 5, 1, 7, 9]
swap 2 (index 0) with 5 (index 2)
heap [5, 3, 2, 1] | sorted [7, 9]
swap root into index 3: [1, 3, 2, 5, 7, 9]
swap 1 (index 0) with 3 (index 1)
heap [3, 1, 2] | sorted [5, 7, 9]
swap root into index 2: [2, 1, 3, 5, 7, 9]
heap [2, 1] | sorted [3, 5, 7, 9]
swap root into index 1: [1, 2, 3, 5, 7, 9]
heap [1] | sorted [2, 3, 5, 7, 9]
result: [1, 2, 3, 5, 7, 9]The sections below walk through this output one step at a time.
Phase 1: Building the Max-Heap
Index 2
a[2] = 9. Its left child is index 5 (value 3). Its right child would be index 6, which is past the end. Since 9 ≥ 3, nothing moves. This subtree is already a heap.
Index 1
a[1] = 2. Its children are index 3 (value 1) and index 4 (value 7). The larger child is 7, and 2 < 7, so the two swap. The 2 lands at index 4. That index's left child would be index 9, which is past the end, so the sift stops.
Array: [5, 7, 9, 1, 2, 3]
Index 0
a[0] = 5. Its children are index 1 (value 7) and index 2 (value 9). The larger child is 9, so 5 and 9 swap. The 5 is now at index 2, and its only child is index 5 (value 3). Since 5 ≥ 3, the sift stops.
Array: [9, 7, 5, 1, 2, 3]
Check the heap property quickly: every element must be no larger than its parent at (i - 1) // 2. Here 7 ≤ 9, 5 ≤ 9, 1 ≤ 7, 2 ≤ 7, and 3 ≤ 5, so the array is a valid max-heap.
Phase 2: Extracting the Maximum Repeatedly
Each round puts the current maximum in its final position and then repairs the smaller heap that remains. The vertical bar separates the heap region a[0:end] from the sorted suffix.
| Round | end | After root swap | Sift-down swaps | After sift-down | Column |
|---|---|---|---|---|---|
| 1 | 5 | `[3, 7, 5, 1, 2, 9]` | 3↔7 | `[7, 3, 5, 1, 2 \ | 9]` |
| 2 | 4 | `[2, 3, 5, 1, 7, 9]` | 2↔5 | `[5, 3, 2, 1 \ | 7, 9]` |
| 3 | 3 | `[1, 3, 2, 5, 7, 9]` | 1↔3 | `[3, 1, 2 \ | 5, 7, 9]` |
| 4 | 2 | `[2, 1, 3, 5, 7, 9]` | none | `[2, 1 \ | 3, 5, 7, 9]` |
| 5 | 1 | `[1, 2, 3, 5, 7, 9]` | none | `[1 \ | 2, 3, 5, 7, 9]` |
Some details of these rounds are worth working through.
- Round 1. The 3 that moved to the root is compared with 7 and 5. It swaps with 7 and lands at index 1. Its children there are 1 and 2, so it stops. The 9 at index 5 is now permanently in place.
- Round 2. With
end = 4, index 2 (value 2 after the swap) has no children inside the heap, because its left child, index 5, is excluded. The sift therefore stops after one swap. - Round 4. The root, 2, has only a left child (index 1, value 1). The right child would be index 2, but
child + 1 < endis false whenend = 2, so the code never looks at the 3 that is already sorted. - Round 5. No loop iteration runs for
end = 0. A heap of one element is sorted by definition.
There were 10 swaps in total: 2 in the build phase, 5 root-to-end swaps, and 3 inside the sort-phase sift-downs.
Invariants to Check While Tracing
At any point in the sort phase, three statements should hold. If one of them fails in your trace, you have found the bug.
a[0:end]satisfies the max-heap property.a[end:]is sorted in ascending order.- Every element in
a[0:end]is ≤ every element ina[end:].
You can check these mechanically:
def check_invariants(a, end):
heap_ok = all(a[(i - 1) // 2] >= a[i] for i in range(1, end))
suffix_ok = all(a[i] <= a[i + 1] for i in range(end, len(a) - 1))
split_ok = end == 0 or end == len(a) or max(a[:end]) <= min(a[end:])
return heap_ok and suffix_ok and split_ok
print(check_invariants([7, 3, 5, 1, 2, 9], 5)) # True
print(check_invariants([5, 3, 9, 1, 7, 2], 4)) # FalseCommon Tracing and Implementation Errors
Passing `n` instead of `end` to `sift_down`
This is the most frequent bug. With the full length passed in, sift-down treats the sorted suffix as part of the heap and pulls large values back into it. Here is round 2 under that bug. After the root swap the array is [2, 3, 5, 1, 7, 9]. The 2 swaps with 5 and lands at index 2. Index 5 now looks like a child, so the 2 swaps with the 9 as well, giving [5, 3, 9, 1, 7, 2]. The 9 has left the sorted region, and the second check_invariants call above catches exactly this state.
Comparing only with the left child
If sift-down skips the a[child + 1] > a[child] test, it can promote the smaller child above the larger one. At index 0 of the build phase it would swap 5 with 7 instead of 9, which leaves 9 as a child of 7 and breaks the heap.
Off-by-one loop bounds
range(n // 2 - 1, -1, -1) includes index 0. Writing range(n // 2 - 1, 0, -1) skips the root, and the "heap" you produce may have a small value on top. In the sort phase, range(len(a) - 1, 0, -1) is correct. Running the loop down to end = 0 is harmless but wastes an iteration.
Using `>` instead of `>=` in the stop test
With if a[root] > a[child]: break, equal keys swap for no reason. The output stays correct but does extra work. Heap sort is not stable either way. Duplicates can end up in a different order no matter which comparison you use, and the stability chapter covers why.
Edge Cases Worth Tracing
| Input | What happens |
|---|---|
| `[]` or `[x]` | Both loops are empty, and the array is returned unchanged. |
| `[2, 1]` | The build phase finds 2 ≥ 1. One root swap gives `[1, 2]`. |
| Already sorted `[1, 2, 3]` | The build phase scrambles it to `[3, 2, 1]`, and the sort phase rebuilds `[1, 2, 3]`. Sorted input brings no speedup. |
| All equal `[4, 4, 4]` | No sift-down swaps occur, but every round still swaps the root with the end. |
The sorted-input row shows that heap sort does not adapt to existing order. It does about the same amount of work on every input, which matches the uniform O(n log n) bound covered in the complexity chapter.
Exercise
Trace the build phase on [4, 10, 3, 5, 1], then perform the first round of the sort phase. Give the array after the build phase and after round 1's sift-down.
Show answer
Build phase: index 1 (value 10) has children 5 and 1, so nothing moves. Index 0 (value 4) swaps with 10, giving [10, 4, 3, 5, 1]. The 4 at index 1 then swaps with its larger child 5, giving [10, 5, 3, 4, 1]. Round 1: swapping the root into index 4 gives [1, 5, 3, 4, 10]. Sift-down with end = 4 swaps 1 with 5, giving [5, 1, 3, 4, 10]. It then swaps 1 with 4 at index 3; index 4 is excluded because end = 4. The result is [5, 4, 3, 1, 10].
Exercise
Trace heap sort on the already sorted array [1, 2, 3]. How many swaps happen in total, and what does this tell you about heap sort on sorted input?
Show answer
Build: index 0 swaps 1 with 3, giving [3, 2, 1] (1 swap). Round end = 2: root swap gives [1, 2, 3], and sift-down swaps 1 with 2, giving [2, 1, 3] (2 swaps). Round end = 1: root swap gives [1, 2, 3] (1 swap). That is 4 swaps in total, for an input that needed none. Heap sort does not take advantage of existing order.
Exercise
A student's heap sort calls sift_down(a, 0, len(a)) in the sort loop. Starting from the max-heap [9, 7, 5, 1, 2, 3], at which round does the sorted suffix first get corrupted, and what is the array at that point?
Show answer
Round 1 happens to work and gives [7, 3, 5, 1, 2, 9]. In round 2 the root swap gives [2, 3, 5, 1, 7, 9]. The 2 swaps with 5 and moves to index 2, and then, because index 5 is wrongly treated as its child, it swaps with 9. The array becomes [5, 3, 9, 1, 7, 2], and the 9 has left the sorted region.