Sub topic 5
Building a Max-Heap from an Unsorted Array
Heap sort needs a max-heap before it can start sorting. Your input, though, is an arbitrary array that probably breaks the heap property in many places. This chapter shows how to rearrange that array into a valid max-heap in place, using only the sift_down function from the previous chapter.
This chapter assumes you are comfortable with:
- The index formulas
parent(i) = (i - 1) // 2,left(i) = 2i + 1,right(i) = 2i + 2 - The max-heap property, where every element is at least as large as its children
- How
sift_down(a, start, end)works and what it assumes about its input - Big-O notation
The Problem in One Sentence
Given an array a of length n, permute its elements so that a[parent(i)] >= a[i] for every i from 1 to n - 1. Use no extra array and as few operations as possible.
There are two natural strategies. The bottom-up strategy repairs subtrees from the leaves toward the root using sift-down. The top-down strategy grows a heap one element at a time using sift-up. Both produce a valid heap. The bottom-up version is faster and is the one heap sort uses.
The Key Precondition of Sift-Down
Sift-down does not fix an arbitrary subtree. It makes one assumption:
This precondition decides the whole algorithm. To use sift-down on node i, both children of i must already be heaps. So you must process children before parents, which means working from the bottom of the tree upward.
Leaves Are Already Heaps
A leaf has no children, so a single-node subtree satisfies the heap property automatically. That means you never need to call sift-down on a leaf.
In a complete binary tree stored in an array of length n, node i has a left child only when 2i + 1 < n. Solving for i gives i <= (n - 2) / 2, so the last node with any child is at index n // 2 - 1. Every index from n // 2 to n - 1 is a leaf.
| n | Last non-leaf index `n // 2 - 1` | Leaf indices |
|---|---|---|
| 1 | -1 (none) | 0 |
| 2 | 0 | 1 |
| 6 | 2 | 3, 4, 5 |
| 7 | 2 | 3, 4, 5, 6 |
| 10 | 4 | 5 to 9 |
About half the array is leaves. Bottom-up construction skips them entirely, and that is part of why it is cheap.
The Bottom-Up Algorithm
Walk the non-leaf indices in decreasing order, from n // 2 - 1 down to 0, and call sift-down on each one. When you reach index i, every index greater than i has already been handled. Its children 2i + 1 and 2i + 2 are greater than i, so they are already roots of valid heaps. The precondition holds every time.
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 is_max_heap(a):
for i in range(1, len(a)):
if a[(i - 1) // 2] < a[i]:
return False
return True
data = [3, 9, 2, 1, 4, 5]
build_max_heap(data)
print(data) # [9, 4, 5, 1, 3, 2]
print(is_max_heap(data)) # TrueTracing the Construction
Take a = [3, 9, 2, 1, 4, 5], so n = 6. The non-leaf indices are 2, 1, and 0. Indices 3, 4, and 5 are leaves.
start = 2. a[2] = 2 has a single child, a[5] = 5. Since 5 > 2, they swap. The array becomes [3, 9, 5, 1, 4, 2]. Index 5 is a leaf, so this sift-down ends.
start = 1. a[1] = 9 has children a[3] = 1 and a[4] = 4. The larger child is 4, and 9 >= 4, so nothing moves.
start = 0. a[0] = 3 has children a[1] = 9 and a[2] = 5. The larger child is 9, so they swap, giving [9, 3, 5, 1, 4, 2]. Sift-down continues at index 1: a[1] = 3 has children 1 and 4. The larger child is 4, so they swap, giving [9, 4, 5, 1, 3, 2]. Index 4 is a leaf, so it stops.
| Step | start | Swaps performed | Array after step |
|---|---|---|---|
| initial | — | — | [3, 9, 2, 1, 4, 5] |
| 1 | 2 | a[2] ↔ a[5] | [3, 9, 5, 1, 4, 2] |
| 2 | 1 | none | [3, 9, 5, 1, 4, 2] |
| 3 | 0 | a[0] ↔ a[1], a[1] ↔ a[4] | [9, 4, 5, 1, 3, 2] |
The element 3 began at the root and sank two levels. A single sift-down can move an element many levels, but only from the top of its subtree downward.
The Alternative: Top-Down Construction with Sift-Up
You can also build a heap the way a priority queue grows. Treat a[0:1] as a heap of size one. Then extend it one element at a time and let each new element climb toward the root while it is larger than its parent.
def sift_up(a, i):
while i > 0:
p = (i - 1) // 2
if a[p] >= a[i]:
break
a[p], a[i] = a[i], a[p]
i = p
def build_max_heap_topdown(a):
for i in range(1, len(a)):
sift_up(a, i)
data = [3, 9, 2, 1, 4, 5]
build_max_heap_topdown(data)
print(data) # [9, 4, 5, 1, 3, 2]On this input the two methods happen to produce the same array. In general they produce different valid heaps, because a set of values usually has many valid heap arrangements.
The difference is cost. In top-down construction, the work for an element depends on its depth, its distance from the root. Most nodes sit near the bottom, so most nodes can be expensive. On ascending input every new element is the largest seen so far and climbs all the way to the root, which costs O(n log n) in total.
In bottom-up construction, the work for a node depends on its height, its distance down to the deepest leaf below it. Most nodes have small height: half are leaves at height 0 and need no work, a quarter have height 1, and so on. The total is O(n). The chapter "Proving That Heap Construction Is Linear" works out the sum. For now you can check the claim by experiment:
import random
def build_counting_swaps(a):
swaps = 0
n = len(a)
for start in range(n // 2 - 1, -1, -1):
root = start
while True:
child = 2 * root + 1
if child >= n:
break
if child + 1 < n and a[child + 1] > a[child]:
child += 1
if a[root] >= a[child]:
break
a[root], a[child] = a[child], a[root]
swaps += 1
root = child
return swaps
def topdown_counting_swaps(a):
swaps = 0
for i in range(1, len(a)):
while i > 0:
p = (i - 1) // 2
if a[p] >= a[i]:
break
a[p], a[i] = a[i], a[p]
swaps += 1
i = p
return swaps
for n in [1_000, 10_000, 100_000]:
ascending = list(range(n))
bu = build_counting_swaps(list(ascending))
td = topdown_counting_swaps(list(ascending))
print(f"n={n:>7} bottom-up={bu:>8} top-down={td:>9} "
f"bottom-up/n={bu / n:.2f}")
assert bu < nThe bottom-up swap count stays below n for every size. The top-down count grows roughly as n log n.
| Property | Bottom-up (sift-down) | Top-down (sift-up) |
|---|---|---|
| Worst-case time | O(n) | O(n log n) |
| Extra space | O(1) | O(1) |
| Needs all data up front | Yes | No, works on a stream |
| Used by heap sort | Yes | Rarely |
| Used by `heapq.heapify` | Yes | No (`heappush` uses sift-up) |
Choose top-down only when elements arrive one at a time and you need a valid heap after each arrival. When the whole array is available, use bottom-up.
Common Errors
Iterating forward. Writing for start in range(n // 2) runs sift-down on the root first, while its subtrees are still unordered. The precondition fails, and the result is often not a heap. On [1, 2, 3, 4, 5, 6, 7], the forward loop leaves 7 at index 2 under a smaller root.
Wrong start index. Starting at n // 2 or n - 1 still works, because sift-down on a leaf exits right away, but it wastes calls. Starting at n // 2 - 2 or lower skips the last parent and can leave a violation at the bottom. For n = 6, starting at index 1 never compares a[2] with a[5].
Off-by-one in range. range(n // 2 - 1, 0, -1) stops before index 0 and never fixes the root. The stop value must be -1.
Passing the wrong end. During construction, end is always n. Heap sort later passes a shrinking end. Copying that loop into build_max_heap produces a heap over only part of the array.
Choosing the wrong child. Comparing against the left child only, or swapping with the smaller child, can push a smaller value above a larger sibling. Always swap with the larger child.
Edge Cases
- Empty array.
n // 2 - 1is-1, the range is empty, and the function returns immediately. - One element. Same result. A single element is a heap.
- Two elements. Only index 0 is processed, and it swaps if
a[1] > a[0]. - Duplicates. The comparison
a[root] >= a[child]stops on ties, so equal keys never swap needlessly. The heap property uses>=, so ties are valid. - Already a heap. Every sift-down exits after one comparison per node. The cost is still O(n), with zero swaps.
- Descending input. A descending array is already a max-heap.
A quick randomized check catches most implementation mistakes:
import random
for _ in range(10_000):
a = [random.randint(0, 20) for _ in range(random.randint(0, 50))]
original = sorted(a)
build_max_heap(a)
assert is_max_heap(a)
assert sorted(a) == original # same elements, only rearranged
print("all checks passed")The second assertion matters. A buggy sift-down that overwrites values instead of swapping them can still pass is_max_heap.
Exercise
Run bottom-up buildmaxheap by hand on [1, 2, 3, 4, 5, 6, 7]. List the start indices processed, the swaps at each, and the final array.
Show answer
n = 7, so start runs 2, 1, 0. start=2: a[2]=3 has children 6 and 7, so it swaps with 7, giving [1, 2, 7, 4, 5, 6, 3]. start=1: a[1]=2 has children 4 and 5, so it swaps with 5, giving [1, 5, 7, 4, 2, 6, 3]. start=0: a[0]=1 has children 5 and 7, so it swaps with 7, giving [7, 5, 1, 4, 2, 6, 3]. It continues at index 2, where 1 has children 6 and 3, so it swaps with 6, giving [7, 5, 6, 4, 2, 1, 3]. Final array: [7, 5, 6, 4, 2, 1, 3], after 4 swaps.
Exercise
A teammate writes the loop as for start in range(n // 2): sift_down(a, start, n). Give a small input where the result is not a max-heap, and explain why.
Show answer
Use [1, 2, 3, 4, 5, 6, 7]. start=0 swaps 1 with 3 and then with 7: [3, 2, 7, 4, 5, 6, 1]. start=1 swaps 2 with 5: [3, 5, 7, 4, 2, 6, 1]. start=2 has 7 above 6 and 1, so nothing moves. The final array [3, 5, 7, 4, 2, 6, 1] has 3 at the root, smaller than both of its children. The root was processed while its subtrees were not yet heaps, so the larger values that later rose to indices 1 and 2 never reached the top.
Exercise
Why is the bottom-up method O(n) while the top-down method is O(n log n) in the worst case, even though both do O(log n) work per node in the worst case?
Show answer
The cost of sift-down at a node is bounded by the node's height, and most nodes have small height: half are leaves at height 0, and a quarter have height 1. The cost of sift-up is bounded by the node's depth, and most nodes are deep, about half at depth log n. Summing heights over all nodes gives O(n). Summing depths gives Θ(n log n).