Heap Construction & d-ary Heaps
Why heapify takes O(n), and choosing the heap’s arity.
Inserting keys into a heap one at a time can cost , yet Floyd's 1964 bottom-up method never needs comparisons. Is that optimal? Counting heaps shows that every method needs about comparisons, the best method known uses , and the true constant is still unknown. The same style of counting decides how many children each heap node should have.
What you’ll learn
- Prove that the heights in an -node heap sum to , so bottom-up heapify makes fewer than swaps and comparisons, while top-down construction needs in the worst case.
- Count the heaps on keys, derive the information-theoretic lower bound of about comparisons for building one, and derive the bound for insert plus extract-min.
- Analyze -ary heaps: height, sift-up and sift-down costs, the best arity for a mix of operations, and why wide nodes help caches.
- Explain the comparison-saving variants: binary search along the insertion path, and the bottom-up sift-down used by CPython's
heapq.
The exact cost of heapify
Heapify sifts down every internal node, from the bottom up. A node of height sinks at most levels, with one swap and at most 2 comparisons per level, so everything hinges on the total height : the sum of the heights of all nodes of an -node heap (heights count edges). Write for the number of 1-bits of , and for the exponent of the largest power of 2 that divides .
Label the nodes level by level, 1-based, so that the children of are and . The ancestors of node are its labels with the last bits removed:
Adding node raises the height of the ancestor exactly when is the first node at depth below it, that is, when the last bits of are all 0. So the total height grows by the number of trailing zero bits of :
Adding 1 to turns its trailing 1-bits into 0s and one 0 into a 1, so , and also grows by exactly . Both quantities are 0 at :
Each swap moves a key one level down inside the subtree being sifted, and each level costs at most 2 comparisons:
Top-down construction, Williams's repeated insertion, is worse in the worst case. If the keys arrive in decreasing order, every new key climbs all the way to the root of the min-heap, so a key inserted at depth makes swaps.
You build a min-heap of keys by inserting them in decreasing order. How many swaps happen in total? (Bottom-up heapify needs at most .)
Show the answer
8194 swaps
Depth holds keys, each climbing levels: , about eight times bottom-up's worst case. In general the total is .
On random input orders the gap shrinks: both methods are linear on average. Simulations give about comparisons and swaps for bottom-up heapify, and about comparisons and swaps for repeated insertion. Doberkat (1984) analyzed the first average, and Hayward and McDiarmid (1991) proved that the second is linear too.
Lower bounds by counting
Place the keys in the tree by a uniformly random permutation. The result is a heap exactly when every node holds the minimum of its own subtree.
The root holds the overall minimum with probability . Given that, the other keys are split between the two subtrees as a uniformly random partition of the right sizes, and each subtree is filled uniformly, so the events in the two subtrees are independent of the root's event and of each other. By induction on the subtrees:
Multiply by . For , a perfect tree of height 2, the subtree sizes are 7, 3, 3 and four 1s, and a computer count of all arrangements agrees:
Floyd's heapify uses up to comparisons. Gonnet and Munro (1982) built heaps with in the worst case, and Li and Reed (2005) raised the lower bound slightly above the counting bound, to . The true worst-case constant lies somewhere in between; it is not known.
A library advertises a comparison-based priority queue with amortized insert and amortized extract-min. What do you conclude?
- It is plausible: Fibonacci heaps already achieve both bounds
- It is plausible when all keys are distinct
- It is impossible: inserts and extract-mins would sort with comparisons
- It is plausible with a 4-ary heap, whose height is half that of a binary heap
Show the answer
C. It is impossible: inserts and extract-mins would sort with comparisons
Sorting keys by comparisons needs comparisons in the worst case. A priority queue with both operations in amortized time would sort in , so the claim is false, or the structure is not comparison-based (integer keys).
d-ary heaps: trading levels for comparisons
Sift-up still compares once per level. Sift-down finds the smallest of up to children with comparisons and compares it with the moving key once more. So, roughly:
| Height at | insert | extract-min | ||
|---|---|---|---|---|
| 2 | 19 | 19 | 38 | 2 |
| 3 | 13 | 13 | 39 | 1.89 |
| 4 | 10 | 10 | 40 | 2 |
| 8 | 7 | 7 | 56 | 2.67 |
| 16 | 5 | 5 | 80 | 4 |
The right depends on the mix of operations. A workload of insertions and decrease-keys and extract-mins costs about comparisons, so the best grows with . Dijkstra's algorithm makes up to decrease-keys and extract-mins, and gives time (Johnson, 1975); the lesson Dijkstra's Algorithm in Depth derives it.
On real hardware comparisons are cheap and cache misses are not. Each level of a sift-down reads one group of siblings, and a 4-ary heap has half as many levels as a binary one. If the array is laid out so that every sibling group starts at a cache line, each level costs at most one miss. LaMarca and Ladner (1996) measured large speedups from such aligned 4-ary heaps once the heap outgrew the cache, and .NET's PriorityQueue is a 4-ary heap.
def sift_down(a, i, d): # d-ary min-heap in a[0..n-1]
n = len(a)
while True:
first = d * i + 1 # children: d*i + 1 .. d*i + d
if first >= n:
return
c = min(range(first, min(first + d, n)), key=a.__getitem__) # d - 1 comparisons
if a[i] <= a[c]: # one more
return
a[i], a[c] = a[c], a[i]
i = cSift-up is unchanged except for the parent, , and heapify starts at the last internal node, .
For large and a workload of extract-mins only, which arity minimizes the worst-case number of comparisons?
- As large as memory allows
Show the answer
B.
Extract-min costs about comparisons: 2 for , about 1.89 for , 2 again for , and more beyond. The continuous minimum of is at .
Saving comparisons on both paths
The lower bound leaves room for about comparisons per insert-plus-extract pair, but a textbook binary heap may spend : up and down. Two classical tricks recover most of the difference.
Binary search on the way up. The keys on the path from the new leaf to the root are sorted, so binary search finds where the new key belongs with comparisons, where is the leaf's depth: about , that is, 5 instead of up to 19 for a million keys. The larger keys on the path still shift down one level each, so the data moves stay .
Bottom-up sift-down on the way down. The key that extract-min moves to the root came from the bottom level, so it is usually large and sinks almost all the way back. Instead of comparing it at every level, walk the hole at the root down to a leaf along the smaller children, with 1 comparison per level, then drop the key in and let it climb, which on average takes only a few comparisons.
def bottom_up_pop(a): # binary min-heap, Floyd's trick
top, last = a[0], a.pop()
if a:
n, i, c = len(a), 0, 1
while c < n: # walk the hole down: 1 comparison per level
if c + 1 < n and a[c + 1] < a[c]:
c += 1
a[i] = a[c]
i, c = c, 2 * c + 1
while i > 0 and last < a[(i - 1) // 2]: # let the last key climb back
a[i] = a[(i - 1) // 2]
i = (i - 1) // 2
a[i] = last
return topCPython's heapq pops this way, and its source comments record the effect: emptying a heap of 1000 random keys took 14,996 comparisons the textbook way and 8,680 with the trick. Our own runs agree, at about 14,990 and 8,670 on average. Wegener's bottom-up heapsort (1993) applies the same idea to sorting.
Gonnet and Munro (1982) pinned these costs down: about comparisons per insertion, and about plus an extremely slowly growing term per replacement of the root, are both necessary and sufficient. Together they come within lower-order terms of the lower bound for the pair.
Key takeaways
- The heights of an -node heap add up to , the exponent of 2 in , so bottom-up heapify makes fewer than swaps and comparisons; its exact worst case is comparisons. Repeated insertion is in the worst case, though linear on average.
- There are heaps on keys, so building one needs about comparisons in the worst case; Li and Reed proved , Gonnet and Munro achieve , and the true constant is open.
- Every comparison-based priority queue sorts, so insert plus extract-min costs at least comparisons amortized: one of the two must be logarithmic.
- A -ary heap has height about : insert and decrease-key get cheaper as grows, extract-min costs about comparisons, and wider nodes touch fewer cache lines.
Check yourself
In the interactive lesson these are scored with your confidence, and what you miss comes back for review.
Bottom-up heapify runs on 12 keys. At most how many swaps can it make?
- 6
- 10
- 12
- 24
Show the answer
B. 10
Swaps are bounded by the total height . In 0-based terms, indices 3, 4 and 5 have height 1, indices 1 and 2 height 2, and the root height 3: .
How many different min-heaps can be formed from the keys 1, 2, 3, 4, 5?
- 24
- 40
- 120
- 8
Show the answer
D. 8
The subtree sizes are 5 (root), 3 (index 1), and 1 for the three leaves, so . Key 1 must be at the root, and the three-node subtree must hold its own minimum on top.
Why must every comparison-based priority queue spend comparisons, amortized, on an insert plus an extract-min?
- Because a heap of keys has height
- Because insertions followed by extract-mins sort the keys, which takes comparisons
- Because extract-min must look at every leaf of the heap
- Because each new key must be compared with every key already stored
Show the answer
B. Because insertions followed by extract-mins sort the keys, which takes comparisons
The reduction from sorting holds for any comparison-based structure, heap-shaped or not. Dividing among pairs of operations gives the bound.
Floyd's trick for extract-min walks the hole at the root down to a leaf along the smaller children, then drops the last key there and lets it climb. Why does that save comparisons?
- The key moved to the root comes from the bottom, so it is usually large and belongs near the bottom: one comparison per level on the way down plus a short climb beats two per level
- It uses binary search on the root-to-leaf path
- It performs no swaps at all, and swaps are what comparisons count
- It only works when the heap is a perfect tree
Show the answer
A. The key moved to the root comes from the bottom, so it is usually large and belongs near the bottom: one comparison per level on the way down plus a short climb beats two per level
The textbook sift-down compares the two children and the moving key at every level, usually all the way down. Walking the hole needs only the children's comparison, and the climb back is short on average: in CPython's measurement, popping 1000 random keys fell from 14,996 comparisons to 8,680.
Further reading
- R. W. Floyd, "Algorithm 245: Treesort 3," Communications of the ACM 7(12) (1964), 701.
- P. A. Suchenek, "Elementary yet precise worst-case analysis of Floyd's heap-construction program," Fundamenta Informaticae 120(1) (2012), 75–92.
- G. H. Gonnet & J. I. Munro, "Heaps on heaps," Automata, Languages and Programming (ICALP 1982), LNCS 140, 282–291.
- Z. Li & B. Reed, "Heap building bounds," Algorithms and Data Structures (WADS 2005), LNCS 3608, 14–23.
- D. E. Knuth, The Art of Computer Programming, vol. 3: Sorting and Searching, 2nd ed. (Addison-Wesley, 1998), section 5.2.3.