Sub topic 10
Proving That Heap Construction Is Linear
The chapter on building a max-heap claimed that bottom-up construction runs in O(n) time. That claim can look wrong at first. The loop calls sift_down about n/2 times, and one sift-down can cost O(log n), so the obvious bound is O(n log n). This chapter shows why that obvious bound is loose and proves the tighter one.
This chapter assumes you know Big-O notation, the sift_down and build_max_heap functions from earlier chapters, and the terms height and depth in a binary tree. A node's height is the number of edges on the longest path from it down to a leaf. A node's depth is the number of edges from the root down to it.
Where the Naive Bound Goes Wrong
The naive argument goes like this:
build_max_heapcallssift_downon indicesn // 2 - 1down to0, which is about n/2 calls.- Each call can swap at most once per level, and the tree has about log₂ n levels.
- So the total is O(n/2 · log n) = O(n log n).
Every step is true, so O(n log n) is a valid upper bound. It just isn't tight. Step 2 charges every node the cost of the worst node, the root. But a sift-down that starts at node i can only travel as far as i's height, and most nodes in a complete binary tree have a very small height.
| Height h | Share of nodes (roughly) | Max swaps per node |
|---|---|---|
| 0 (leaves) | 1/2 | 0 |
| 1 | 1/4 | 1 |
| 2 | 1/8 | 2 |
| 3 | 1/16 | 3 |
| h | 1/2^(h+1) | h |
Half the nodes are leaves and do no work. A quarter do at most one swap. Only one node, the root, can do the full log₂ n swaps. The expensive nodes are rare, and the common nodes are cheap.
Counting Work by Height
In a heap with n nodes, there are at most ⌈n / 2^(h+1)⌉ nodes of height h. A sift-down starting at a node of height h does at most h swaps and at most 2 comparisons per level, so its cost is O(h). Adding up over all heights gives:
T(n) ≤ Σ over h from 0 to ⌊log₂ n⌋ of ⌈n / 2^(h+1)⌉ · c·h
Leave out the ceiling for a moment (the next section gives an exact count that needs no rounding). The sum then becomes:
T(n) ≤ (c·n / 2) · Σ h / 2^h
The question is now whether Σ h/2^h stays bounded as more terms are added. It does.
Evaluating Σ h / 2^h
Let S = 1/2 + 2/4 + 3/8 + 4/16 + ⋯
Halve it, so that each term moves one position to the right:
S/2 = 1/4 + 2/8 + 3/16 + ⋯
Subtract term by term. Each pair of terms with the same denominator differs by exactly that denominator's reciprocal:
S − S/2 = 1/2 + 1/4 + 1/8 + 1/16 + ⋯ = 1
So S/2 = 1, and S = 2. The infinite sum is 2, which means every finite partial sum is below 2. Substituting back:
T(n) ≤ (c·n / 2) · 2 = c·n = O(n)
Any algorithm that builds a heap must look at every element at least once, so construction is also Ω(n). Together that gives Θ(n).
An Exact Count: Fewer Than n Swaps
The asymptotic argument hides a constant, but for swaps there is a sharp, exact bound. Each sift-down does at most as many swaps as the height of its starting node, so:
total swaps ≤ sum of the heights of all nodes
For a complete binary tree with n nodes, the sum of all node heights equals n − s(n), where s(n) is the number of 1 bits in the binary form of n. You can check it on small trees:
| n | Heights of nodes 0..n−1 | Sum | n − s(n) |
|---|---|---|---|
| 3 | 1, 0, 0 | 1 | 3 − 2 = 1 |
| 4 | 2, 1, 0, 0 | 3 | 4 − 1 = 3 |
| 5 | 2, 1, 0, 0, 0 | 3 | 5 − 2 = 3 |
| 7 | 2, 1, 1, 0, 0, 0, 0 | 4 | 7 − 3 = 4 |
So bottom-up construction never does more than n − 1 swaps. Comparisons are bounded too. Each loop iteration inside sift_down does at most 2 comparisons, and a call runs one more iteration than it does swaps. That gives at most 2·(swaps + n/2) < 3n comparisons in total.
The chart below shows the bound for a perfect tree with n = 1023 (10 levels). The columns are the swap budget at each height: number of nodes times height.
Height 0 contributes nothing, heights 1 and 2 contribute the most, and the root contributes only 9. The total stays below n because each time the height goes up by one, the node count halves.
Checking the Bound Empirically
The script below adds counters to sift_down and runs construction on ascending arrays. An ascending array is a hard input for a max-heap, because every subtree root starts out as the smallest value in its subtree and has to sink all the way down. The script asserts the exact swap bound and the 3n comparison bound, and prints the per-element ratios.
def sift_down_counted(a, start, end, stats):
root = start
while True:
child = 2 * root + 1
if child >= end:
break
if child + 1 < end:
stats["cmp"] += 1
if a[child + 1] > a[child]:
child += 1
stats["cmp"] += 1
if a[root] >= a[child]:
break
a[root], a[child] = a[child], a[root]
stats["swaps"] += 1
root = child
def build_max_heap_counted(a):
stats = {"swaps": 0, "cmp": 0}
n = len(a)
for start in range(n // 2 - 1, -1, -1):
sift_down_counted(a, start, n, stats)
return stats
def is_max_heap(a):
return all(a[(i - 1) // 2] >= a[i] for i in range(1, len(a)))
print(f"{'n':>9} {'swaps':>9} {'bound':>9} {'swaps/n':>8} {'cmp/n':>7}")
for n in [10, 100, 1_000, 10_000, 100_000, 1_000_000]:
a = list(range(n)) # ascending: a hard case for a max-heap
stats = build_max_heap_counted(a)
bound = n - bin(n).count("1")
assert is_max_heap(a)
assert stats["swaps"] <= bound
assert stats["cmp"] < 3 * n
print(f"{n:>9} {stats['swaps']:>9} {bound:>9} "
f"{stats['swaps'] / n:>8.3f} {stats['cmp'] / n:>7.3f}")When you run it, all the assertions pass. The swaps/n column stays below 1 and the cmp/n column stays below 3, even though n grows by a factor of 100,000. If construction were Θ(n log n), these ratios would keep growing with log n.
Why Sift-Up Construction Is Not Linear
Another way to build a heap is to insert elements one at a time. Each new element goes at the end of the array and sifts up toward the root. That method is O(n log n) in the worst case, and the reason is the same counting argument turned around.
- Sift-down cost depends on a node's height. Most nodes have small height, so the total is small.
- Sift-up cost depends on a node's depth. Most nodes have large depth, because about half of them are leaves at depth ⌊log₂ n⌋.
For sift-up, the bottom half of the nodes can each pay about log₂ n swaps. On an ascending input, every insert is a new maximum and travels all the way to the root, so the total is Θ(n log n).
Common Misreadings
Two other mistakes come up often:
- Charging by depth instead of height. If your sum uses "nodes at depth d times d", you have analyzed sift-up, not sift-down, and you will get O(n log n).
- Dropping the ceiling carelessly. ⌈n / 2^(h+1)⌉ can be 1 when n / 2^(h+1) is much smaller than 1, near the root. The exact sum-of-heights identity avoids this issue. In the asymptotic argument, the extra terms from rounding add at most Σ h ≤ O(log² n), which does not change O(n).
The linear build still has practical value. When you only need the top k items, or a priority queue that starts with n known elements, heapify costs O(n) instead of the O(n log n) of n separate inserts. Python's heapq.heapify uses the bottom-up method for this reason.
Exercise
A complete binary tree has n = 12 nodes. Use the identity to find the maximum total number of swaps that bottom-up construction can perform, then confirm it by listing each node's height.
Show answer
12 in binary is 1100, which has two 1 bits, so the bound is 12 − 2 = 10. Heights by index: node 0 has height 3, nodes 1 and 2 have height 2, nodes 3, 4 and 5 have height 1 (node 5's only child is node 11), and nodes 6 through 11 are leaves with height 0. Sum: 3 + 2 + 2 + 1 + 1 + 1 = 10.
Exercise
Evaluate Σ h / 3^h for h ≥ 0 with the shifting trick. What does it tell you about construction cost in a ternary (3-ary) heap, counted in levels moved?
Show answer
Let S = 1/3 + 2/9 + 3/27 + ⋯. Then S/3 = 1/9 + 2/27 + ⋯, and S − S/3 = 1/3 + 1/9 + ⋯ = 1/2. So (2/3)S = 1/2 and S = 3/4. The sum is still a constant, so a 3-ary heap also builds in O(n) levels moved. Each level costs up to 3 comparisons instead of 2, which changes the constant but not the linear bound.
Exercise
Change the script to build the heap by inserting elements one at a time with sift-up, using an ascending input. How does swaps/n behave as n grows, and why?
Show answer
swaps/n grows roughly like log₂ n (about 8 at n = 1,000 and about 18 at n = 1,000,000). Each new element in an ascending input is the largest so far, so it climbs from its depth all the way to the root. Most nodes sit near depth log₂ n, so the total is Θ(n log n).