Sub topic 9
Building a heap in linear time
This chapter assumes you know the array layout of a binary heap (parent of i is (i - 1) // 2, children are 2i + 1 and 2i + 2) and the sift-down operation. You should also be comfortable with Big-O notation.
The problem
You have an unsorted list of n items and want a heap. The obvious method pushes each item in turn. Each push costs O(log n), so the total is O(n log n).
A better method, usually called heapify or build-heap, does the job in O(n). Python's heapq.heapify uses it.
The bottom-up method
Treat the array as a complete binary tree that does not yet satisfy the heap property. Then fix it from the bottom:
- Leaves are already valid one-item heaps. They occupy indexes
n // 2ton - 1, so skip them. - Start at the last non-leaf index,
n // 2 - 1. - Sift each node down, moving toward index 0.
When you sift down node i, both of its subtrees are already heaps. Sift down then restores the heap property for the whole subtree rooted at i.
def sift_down(a, i, n):
while True:
child = 2 * i + 1
if child >= n:
return
if child + 1 < n and a[child + 1] < a[child]:
child += 1
if a[i] <= a[child]:
return
a[i], a[child] = a[child], a[i]
i = child
def build_heap(a):
n = len(a)
for i in range(n // 2 - 1, -1, -1):
sift_down(a, i, n)
def is_heap(a):
return all(a[(i - 1) // 2] <= a[i] for i in range(1, len(a)))
data = [9, 4, 7, 1, 6, 2]
build_heap(data)
print(data) # [1, 4, 2, 9, 6, 7]
print(is_heap(data)) # TrueHere n is 6, so the loop starts at index 2. Sifting 7 swaps it with 2. Sifting 4 swaps it with 1. Sifting 9 swaps it with 1, then with 4, and the array ends up as [1, 4, 2, 9, 6, 7].
Why it is O(n)
A sift-down from a node can move at most as far as the height of that node, which is the distance to the deepest leaf below it. Most nodes are near the bottom, where heights are small.
The table shows a perfect tree of 15 nodes. It compares the worst-case swaps of bottom-up building (sift down by height) with repeated insertion (sift up by depth).
| Level | Nodes | Height | Depth | Bottom-up swaps | Repeated-push swaps |
|---|---|---|---|---|---|
| Leaves | 8 | 0 | 3 | 0 | 24 |
| Next up | 4 | 1 | 2 | 4 | 8 |
| Next up | 2 | 2 | 1 | 4 | 2 |
| Root | 1 | 3 | 0 | 3 | 0 |
| Total | 15 | 11 | 34 |
For general n, about n / 2^(h+1) nodes have height h. The total work is bounded by the sum over h of (n / 2^(h+1)) · h. This is n/2 times the sum of h / 2^h, and that series converges to 2. So the total is at most about n swaps, which is O(n).
Repeated insertion is expensive because half the nodes are leaves, and each leaf can sift up about log n levels. Bottom-up building gives the leaves no work and the root, the single node that can travel the full height, the most.
Common errors
- Sifting up instead of down. Looping forward and sifting up works, but it is the O(n log n) method in disguise.
- Looping from the front. Sift down assumes both subtrees are already heaps. Going from index 0 upward breaks that assumption, and the result is not a heap.
- Starting at
n - 1orn // 2. Starting atn - 1is harmless but wastes time on leaves. Starting atn // 2is wrong because it skips the last non-leaf node when n is even. - Expecting a sorted list. A heap only guarantees
a[0]is the minimum. The array above is not sorted. - Forgetting that heapify works in place.
heapq.heapify(x)modifiesxand returnsNone.
Exercise
Build a min-heap from [5, 3, 8, 1] with the bottom-up method. Which index do you start at, and what is the final array?
Show answer
With n = 4, start at index 4 // 2 - 1 = 1. Sifting 3 down swaps it with its only child 1, giving [5, 1, 8, 3]. Then sift 5 at index 0 down. The smaller child is 1, so swap to get [1, 5, 8, 3]. Then 5 at index 1 has the child 3, so swap to get [1, 3, 8, 5].