Sub topic 6
Heap Sort: Swap the Root, Shrink, Repeat
This chapter assumes you already have the pieces from earlier chapters: the index formulas parent(i), left(i), and right(i), the max-heap property, a working sift_down(a, start, end), and build_max_heap(a). It also assumes you are comfortable with Python loops, slicing, and Big-O notation. Here we put those pieces together into the full sorting algorithm. We look at the invariant that makes it correct, the boundary details that commonly break implementations, and the edge cases you should test.
The Core Idea
A max-heap is good at one thing: it keeps the largest element at index 0. Heap sort takes advantage of that over and over.
- Turn the whole array into a max-heap.
- The maximum is at
a[0]. Swap it with the last element of the heap. The maximum is now in its final sorted position. - Treat that last slot as no longer part of the heap. The heap shrinks by one.
- The element just swapped into
a[0]probably breaks the heap property. Sift it down within the smaller heap. - Repeat until the heap holds a single element.
The algorithm uses no second array. The same array holds two regions side by side: an unsorted max-heap on the left and a sorted suffix on the right. Each pass moves the boundary between them one step to the left.
Why a Max-Heap Produces Ascending Order
At first it seems backwards that a max-heap gives ascending order. The reason is where the extracted elements land. Each extraction puts the current maximum at the right edge of the shrinking heap. The largest element goes to index n - 1, the second largest to n - 2, and so on. The array fills from right to left with values that keep getting smaller, so reading it left to right gives ascending order.
To sort in descending order, you can use a min-heap (flip every comparison in sift_down), or you can sort ascending and reverse the result. Don't try to get descending order by pulling elements off the front of the array. That breaks the in-place layout.
The Implementation
Here is the complete, runnable version, with the helper functions from earlier chapters included so the block stands 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]The heap_sort function has only four lines, and every one of them matters.
The loop bounds
range(len(a) - 1, 0, -1) produces end = n-1, n-2, ..., 1. In each iteration, end is the index of the slot that is about to be filled with its final value, and it is also the exclusive upper bound of the heap that remains after the swap.
The loop stops before end = 0. When only a[0] is left in the heap, it is the smallest element and is already in place. Running one more iteration would swap a[0] with itself and sift down a heap of size zero. That does no harm but also does nothing.
The exclusive `end` passed to sift-down
After the swap, the heap is a[0:end], and a[end] belongs to the sorted region. The call sift_down(a, 0, end) uses end as an exclusive limit, so sift_down never compares against a[end] and never swaps with it. This single boundary is the most common place for heap sort bugs.
Why only index 0 needs repair
Before the swap, a[0:end+1] is a valid max-heap. The swap changes exactly two positions. Position end leaves the heap, so it no longer counts. Position 0 now holds an element that used to be a leaf. Every other parent-child pair inside a[0:end] is unchanged, so the subtrees rooted at indices 1 and 2 are still valid max-heaps. That is exactly the precondition sift_down needs: the two subtrees below the root are heaps and only the root may be out of place. A single sift-down from index 0 is therefore enough. You don't need to rebuild the heap.
The Loop Invariant
You can state the correctness argument precisely. At the start of each iteration with a given end:
a[0:end+1]is a max-heap.a[end+1:]holds then - end - 1largest elements of the input, in ascending order.- Every element in
a[0:end+1]is less than or equal to every element ina[end+1:].
Initialization. After build_max_heap, end = n - 1. The whole array is a heap and the sorted region is empty, so all three statements hold.
Maintenance. a[0] is the maximum of the heap, and by the third statement it is no larger than anything in the sorted region. Swapping it into a[end] extends the sorted region by one element and keeps that region sorted. Sifting down restores the heap property on a[0:end]. Decrementing end re-establishes all three statements.
Termination. When the loop exits, end has reached 0. a[1:] is sorted and holds the n - 1 largest elements, and a[0] is no larger than any of them. The whole array is sorted.
You can turn the invariant into executable assertions. This is the most effective way to debug your own implementation:
import random
def is_max_heap(a):
for i in range(1, len(a)):
if a[(i - 1) // 2] < a[i]:
return False
return True
def heap_sort_checked(a):
build_max_heap(a)
assert is_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)
assert is_max_heap(a[:end]), "heap region broken"
assert a[end:] == sorted(a[end:]), "sorted region out of order"
assert max(a[:end]) <= a[end], "heap holds an element larger than the sorted region"
return a
for trial in range(2000):
n = random.randint(0, 30)
xs = [random.randint(-5, 5) for _ in range(n)]
expected = sorted(xs)
assert heap_sort_checked(xs[:]) == expected, xs
print("all randomized tests passed")This block reuses sift_down and build_max_heap from the previous block, so run the two together. The narrow value range -5..5 is deliberate. It forces many duplicates, which exercise the >= and > comparisons in sift_down.
One Pass in Detail
The next chapter traces a full run. Here is a single iteration, to tie the code to the picture. Start from the valid max-heap [9, 7, 8, 3, 5, 6] with end = 5.
| Step | Array | Heap region | Note |
|---|---|---|---|
| Before swap | `[9, 7, 8, 3, 5, 6]` | `a[0:6]` | 9 is the maximum |
| Swap `a[0]`, `a[5]` | `[6, 7, 8, 3, 5, 9]` | `a[0:5]` | 9 is final; 6 is at the root |
| Sift: compare 6 with children 7, 8 | `[8, 7, 6, 3, 5, 9]` | `a[0:5]` | swap with larger child 8 at index 2 |
| Sift: index 2 has child index 5 | `[8, 7, 6, 3, 5, 9]` | `a[0:5]` | 5 is not less than `end` = 5, so stop |
Look at the last row. Index 2's left child would be index 5, which holds the 9. Because end = 5 is exclusive, sift_down correctly ignores it. With an off-by-one bound, the 6 would have been compared against the 9 and swapped with it.
Edge Cases
| Input | What happens | Result |
|---|---|---|
| `[]` | `build_max_heap` loop runs zero times; `range(-1, 0, -1)` is empty | `[]` |
| `[x]` | No non-leaf nodes; `range(0, 0, -1)` is empty | `[x]` |
| Already sorted ascending | Build moves elements around; sort proceeds normally | Sorted, with no shortcut |
| All equal | `a[root] >= a[child]` stops every sift immediately | Sorted, few swaps |
| Mixed types like `[1, "a"]` | `>` raises `TypeError` | Exception, as with `sorted` |
Sorted input does not get a fast path. Building a max-heap from ascending data actually scrambles it, and the extraction phase still does about n log n comparisons. Heap sort doesn't adapt to existing order, which is part of the trade-off discussed in later chapters.
Common Mistakes
| Mistake | Symptom | Fix |
|---|---|---|
| Skipping `build_max_heap` | Wrong output on most inputs | Always build before extracting |
| `sift_down(a, 0, end + 1)` | Large values reappear near the front | Pass the exclusive bound `end` |
| Loop `range(len(a), 0, -1)` | `IndexError` on `a[len(a)]` | Start at `len(a) - 1` |
| Comparing with only the left child | Heap property silently violated | Pick the larger of both children, checking `child + 1 < end` |
| Using `<` instead of `>=` for the stop test | Extra swaps of equal keys; still correct, but slower | Stop when root is not smaller than its larger child |
| Returning a new list | Callers expect in-place mutation | Mutate `a`; return `None` like `list.sort` |
Sorting by a Key
Real data often needs sorting by a field, not by the whole value. The change is local to the comparisons. Thread a key function through sift_down and leave the outer loop alone:
def sift_down_key(a, start, end, key):
root = start
while True:
child = 2 * root + 1
if child >= end:
break
if child + 1 < end and key(a[child + 1]) > key(a[child]):
child += 1
if key(a[root]) >= key(a[child]):
break
a[root], a[child] = a[child], a[root]
root = child
def heap_sort_key(a, key=lambda x: x):
n = len(a)
for start in range(n // 2 - 1, -1, -1):
sift_down_key(a, start, n, key)
for end in range(n - 1, 0, -1):
a[0], a[end] = a[end], a[0]
sift_down_key(a, 0, end, key)
people = [("ana", 31), ("bo", 25), ("cy", 40), ("di", 25)]
heap_sort_key(people, key=lambda p: p[1])
print([p[1] for p in people]) # [25, 25, 31, 40]The ages come out in order. The two people aged 25 may not keep their original relative order, though. That is the stability question, covered in its own chapter.
Exercise
Start from the max-heap [8, 7, 6, 3, 5, 9], where the heap region is a[0:5] and 9 is already sorted. Perform the next iteration (end = 4): do the swap, then the sift-down. Write the array after each step.
Show answer
Swap a[0] and a[4]: [5, 7, 6, 3, 8, 9]. The heap is now a[0:4]. Sift down from index 0: the children are 7 (index 1) and 6 (index 2), so swap 5 with 7 to get [7, 5, 6, 3, 8, 9]. At index 1 the left child is index 3, which holds 3, and 3 < 4 so it is inside the heap. Since 5 >= 3, stop. Final array: [7, 5, 6, 3, 8, 9].
Exercise
A colleague writes the extraction loop as for end in range(len(a) - 1, -1, -1), so it also runs with end = 0. Is the result still correct, and is anything wasted?
Show answer
It is still correct. With end = 0, the code swaps a[0] with itself and calls sift_down(a, 0, 0), which exits immediately because child = 1 >= 0. The only cost is one useless iteration, which is why the standard loop stops at end = 1.
Exercise
Explain why, after swapping the root with a[end], a single sift_down from index 0 restores the heap on a[0:end], instead of requiring a full rebuild.
Show answer
The swap changes only positions 0 and end. Position end leaves the heap. All other parent-child relationships in a[0:end] are unchanged, so the subtrees rooted at indices 1 and 2 are still valid max-heaps. Sift-down needs exactly that precondition: only the root may violate the property. One sift-down from index 0 therefore fixes the whole heap in O(log n) time.