Sub topic 5
Building a Max-Heap from an Unsorted Array
This chapter assumes you know zero-based array indexing, the parent and child index formulas (left(i) = 2i + 1, right(i) = 2i + 2), the max-heap property, and the sift_down function from the previous chapter. The goal here is to turn any unordered array into a valid max-heap in place, which is the first phase of heap sort.
The idea: fix subtrees from the bottom up
sift_down can repair a node only when both of its child subtrees are already max-heaps. That rule tells you the order to work in. If you process nodes from the bottom of the tree toward the root, every node's children have already been fixed by the time you reach it.
Leaves need no work. A single node is always a valid heap. In an array of length n, the leaves sit at indices n // 2 through n - 1. The last node with at least one child is therefore at index n // 2 - 1. The construction starts there and walks backward to index 0.
The code
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 build_max_heap(a):
n = len(a)
for start in range(n // 2 - 1, -1, -1):
sift_down(a, start, n)
data = [5, 2, 9, 1, 7, 3]
build_max_heap(data)
print(data) # [9, 7, 5, 1, 2, 3]Tracing the example
Start with [5, 2, 9, 1, 7, 3], so n = 6 and the loop visits indices 2, 1, 0.
| Step | Index visited | Action | Array after |
|---|---|---|---|
| 1 | 2 (value 9) | 9 ≥ child 3, no swap | `[5, 2, 9, 1, 7, 3]` |
| 2 | 1 (value 2) | larger child is 7; swap | `[5, 7, 9, 1, 2, 3]` |
| 3 | 0 (value 5) | larger child is 9; swap, then 5 ≥ child 3, stop | `[9, 7, 5, 1, 2, 3]` |
In step 3 the 5 moves down only one level, because its new child 3 is smaller. One call to sift_down can move a value several levels when it needs to.
Common errors
- Skipping the root.
range(n // 2 - 1, 0, -1)stops at index 1. The stop value must be-1so that index 0 is included. - Starting too late. Starting at
n - 1gives correct results, but it spends calls on leaves, wheresift_downexits right away. - Wrong
endargument. During construction the whole array is the heap, so passn. The smallerendvalues belong to the sorting phase.
Why not insert elements one at a time?
You could also build a heap by appending each element and letting it "sift up" toward the root. That method costs O(log n) per insertion, so O(n log n) in total. The bottom-up method costs only O(n). Most nodes sit near the leaves, where sift-down has very little distance to travel. A later chapter proves that bound. For now, remember that bottom-up construction is both simpler and faster.
Exercise
Run buildmaxheap by hand on [3, 1, 6, 5, 2, 4]. Which indices are visited, and what is the final array?
Show answer
n = 6, so the loop visits indices 2, 1, 0. Index 2 (value 6) is larger than its child 4, so nothing changes. Index 1 (value 1) swaps with its larger child 5, giving [3, 5, 6, 1, 2, 4]. Index 0 (value 3) swaps with 6, giving [6, 5, 3, 1, 2, 4]. The 3 then sits at index 2, and its child 4 is larger, so they swap. The final array is [6, 5, 4, 1, 2, 3].
Exercise
Someone writes the loop as for start in range(0, n // 2). Show that this fails on [1, 2, 3, 4, 5, 6, 7].
Show answer
Index 0 swaps 1 with 3 and then with 7, giving [3, 2, 7, 4, 5, 6, 1]. Index 1 swaps 2 with 5, giving [3, 5, 7, 4, 2, 6, 1]. Index 2 (value 7) needs no change. The root is 3 but its child is 7, so the result is not a max-heap. Processing top-down lets large values climb only partway up the tree.