Sub topic 10
Proving That Heap Construction Is Linear
This chapter assumes you know Big-O notation, can follow a sum written with Σ, and have read the earlier chapters on sift_down and build_max_heap. The goal is to show why calling sift_down on about n/2 nodes costs O(n) in total, not O(n log n).
The naive bound and why it is loose
A single sift_down can take up to log₂ n swaps, and build_max_heap calls it about n/2 times. Multiplying gives O(n log n). That bound holds, but it is loose. It charges every node for the worst-case trip from the root, and most nodes start much closer to the bottom.
The key fact is that sift-down from a node can travel at most as far as that node's height. A node's height is the number of edges on the longest path from it down to a leaf. Leaves have height 0, and the root has height ⌊log₂ n⌋.
Counting nodes by height
In a complete binary tree with n nodes, about half the nodes are leaves, about a quarter sit at height 1, and about an eighth at height 2. In general:
- The number of nodes at height h is at most ⌈n / 2^(h+1)⌉.
- Each of those nodes costs at most h swaps (and about 2h comparisons).
The work therefore concentrates in the lower levels, where there are many nodes but each one costs little. For a perfect tree with 15 nodes, the maximum swaps per level look like this:
| Height h | Nodes at h | Max swaps per node | Max swaps for level |
|---|---|---|---|
| 0 | 8 | 0 | 0 |
| 1 | 4 | 1 | 4 |
| 2 | 2 | 2 | 4 |
| 3 | 1 | 3 | 3 |
The total is 11 swaps for 15 nodes, which is fewer than n.
The sum
Add up the cost over all heights:
T(n) ≤ Σ (h = 0 to ⌊log n⌋) ⌈n / 2^(h+1)⌉ · h ≤ n · Σ (h = 0 to ∞) h / 2^(h+1) (ignoring the rounding from the ceiling, which adds only lower-order terms)
The infinite series Σ h / 2^h converges to 2, so Σ h / 2^(h+1) = 1. That gives T(n) ≤ n plus lower-order terms, so T(n) = O(n). Every element must be examined at least once, so the bound is tight: building a heap takes Θ(n).
For a perfect tree with k levels (n = 2^k − 1), the exact sum of heights is n − k = n − log₂(n + 1). This is the maximum number of swaps.
Checking the bound empirically
The script below counts swaps during build_max_heap. An ascending array makes every sifted element the smallest in its subtree, so each one travels all the way to a leaf.
import random
def sift_down_count(a, start, end):
swaps = 0
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
swaps += 1
return swaps
def build_max_heap_count(a):
n = len(a)
return sum(sift_down_count(a, s, n) for s in range(n // 2 - 1, -1, -1))
for n in [1_000, 10_000, 100_000, 1_000_000]:
ascending = list(range(n))
shuffled = random.sample(range(n), n)
s1 = build_max_heap_count(ascending)
s2 = build_max_heap_count(shuffled)
print(f"n={n:>9} ascending swaps/n={s1 / n:.3f} random swaps/n={s2 / n:.3f}")Both ratios stay below 1 and stay flat as n grows by a factor of 1,000. An O(n log n) process would show the ratio growing with log n.
Exercise
For a perfect heap with n = 31 nodes, what is the maximum total number of swaps buildmaxheap can perform? Show the per-height breakdown.
Show answer
The heights are 0 through 4, with 16, 8, 4, 2, and 1 nodes. The maximum is 16·0 + 8·1 + 4·2 + 2·3 + 1·4 = 26, which matches n − k = 31 − 5.
Exercise
Why does the same counting argument fail to show linear time for building a heap through repeated insertion with sift-up?
Show answer
Sift-up costs a node's depth, and most nodes are deep. About n/2 leaves each sit at depth about log₂ n, so the sum is dominated by the bottom level and comes to Θ(n log n) in the worst case.