Simple Algorithm
Algorithms & Data Structures · Optimal · 24 min

Heap Construction & d-ary Heaps

Why heapify takes O(n), and choosing the heap’s arity.

Inserting nn keys into a heap one at a time can cost Θ(nlog⁡n)\Theta(n\log n), yet Floyd's 1964 bottom-up method never needs 2n2n comparisons. Is that optimal? Counting heaps shows that every method needs about 1.36n1.36n comparisons, the best method known uses 1.625n1.625n, 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 nn-node heap sum to n−s2(n)n - s_2(n), so bottom-up heapify makes fewer than nn swaps and 2n2n comparisons, while top-down construction needs Θ(nlog⁡n)\Theta(n\log n) in the worst case.
  • Count the heaps on nn keys, derive the information-theoretic lower bound of about 1.364n1.364n comparisons for building one, and derive the log⁡2n!\log_2 n! bound for insert plus extract-min.
  • Analyze dd-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 hh sinks at most hh levels, with one swap and at most 2 comparisons per level, so everything hinges on the total height H(n)H(n): the sum of the heights of all nodes of an nn-node heap (heights count edges). Write s2(n)s_2(n) for the number of 1-bits of nn, and e2(n)e_2(n) for the exponent of the largest power of 2 that divides nn.

DerivationProof: add the nodes one at a time
  1. ancestors of N:⌊N/2⌋, ⌊N/4⌋, …, 1\text{ancestors of } N:\quad \lfloor N/2 \rfloor,\ \lfloor N/4 \rfloor,\ \dots,\ 1

    Label the nodes 1,…,n1, \dots, n level by level, 1-based, so that the children of vv are 2v2v and 2v+12v+1. The ancestors of node NN are its labels with the last kk bits removed:

  2. H(N)−H(N−1)=tz⁡(N)H(N) - H(N-1) = \operatorname{tz}(N)

    Adding node NN raises the height of the ancestor ⌊N/2k⌋\lfloor N/2^k\rfloor exactly when NN is the first node at depth kk below it, that is, when the last kk bits of NN are all 0. So the total height grows by the number of trailing zero bits of NN:

  3. H(n)=∑N=1ntz⁡(N)=n−s2(n)H(n) = \sum_{N=1}^{n} \operatorname{tz}(N) = n - s_2(n)

    Adding 1 to N−1N-1 turns its tz⁡(N)\operatorname{tz}(N) trailing 1-bits into 0s and one 0 into a 1, so s2(N)−s2(N−1)=1−tz⁡(N)s_2(N) - s_2(N-1) = 1 - \operatorname{tz}(N), and N−s2(N)N - s_2(N) also grows by exactly tz⁡(N)\operatorname{tz}(N). Both quantities are 0 at N=1N = 1:

  4. swaps≤n−s2(n)<n,comparisons≤2(n−s2(n))<2n\text{swaps} \le n - s_2(n) < n, \qquad \text{comparisons} \le 2\big(n - s_2(n)\big) < 2n

    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 dd makes dd swaps.

Predict before you look

You build a min-heap of 1023=210−11023 = 2^{10} - 1 keys by inserting them in decreasing order. How many swaps happen in total? (Bottom-up heapify needs at most 1023−10=10131023 - 10 = 1013.)

Show the answer

8194 swaps

Depth dd holds 2d2^d keys, each climbing dd levels: ∑d=09d 2d=(9−1) 210+2=8194\sum_{d=0}^{9} d\,2^d = (9-1)\,2^{10} + 2 = 8194, about eight times bottom-up's worst case. In general the total is ∑j=1n⌊log⁡2j⌋=Θ(nlog⁡n)\sum_{j=1}^{n}\lfloor\log_2 j\rfloor = \Theta(n\log n).

On random input orders the gap shrinks: both methods are linear on average. Simulations give about 1.88n1.88n comparisons and 0.74n0.74n swaps for bottom-up heapify, and about 2.28n2.28n comparisons and 1.28n1.28n 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

DerivationProof
  1. Pr⁡[heap]=Pr⁡[⋂v{v holds the minimum of its subtree}]\Pr[\text{heap}] = \Pr\Big[\textstyle\bigcap_v \{v \text{ holds the minimum of its subtree}\}\Big]

    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.

  2. Pr⁡[heap]=1n Pr⁡[left is a heap] Pr⁡[right is a heap]=∏v1sv\Pr[\text{heap}] = \frac{1}{n}\,\Pr[\text{left is a heap}]\,\Pr[\text{right is a heap}] = \prod_v \frac{1}{s_v}

    The root holds the overall minimum with probability 1/n1/n. 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:

  3. Heaps⁡(7)=7!7⋅3⋅3=504063=80\operatorname{Heaps}(7) = \frac{7!}{7\cdot 3\cdot 3} = \frac{5040}{63} = 80

    Multiply by n!n!. For n=7n = 7, a perfect tree of height 2, the subtree sizes are 7, 3, 3 and four 1s, and a computer count of all 50405040 arrangements agrees:

Floyd's heapify uses up to 2n2n comparisons. Gonnet and Munro (1982) built heaps with 1.625n1.625n in the worst case, and Li and Reed (2005) raised the lower bound slightly above the counting bound, to 1.37n+o(n)1.37n + o(n). The true worst-case constant lies somewhere in between; it is not known.

Check your understanding

A library advertises a comparison-based priority queue with O(1)O(1) amortized insert and O(1)O(1) amortized extract-min. What do you conclude?

  1. It is plausible: Fibonacci heaps already achieve both bounds
  2. It is plausible when all keys are distinct
  3. It is impossible: nn inserts and nn extract-mins would sort with O(n)O(n) comparisons
  4. It is plausible with a 4-ary heap, whose height is half that of a binary heap
Show the answer

C. It is impossible: nn inserts and nn extract-mins would sort with O(n)O(n) comparisons

Sorting nn keys by comparisons needs ⌈log⁡2n!⌉=Ω(nlog⁡n)\lceil\log_2 n!\rceil = \Omega(n\log n) comparisons in the worst case. A priority queue with both operations in O(1)O(1) amortized time would sort in O(n)O(n), 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 dd children with d−1d-1 comparisons and compares it with the moving key once more. So, roughly:

Tinsert, Tdecrease-key ≈ log⁡dn=log⁡2nlog⁡2d,Textract-min ≈ dlog⁡dn=dlog⁡2d log⁡2nT_{\text{insert}},\ T_{\text{decrease-key}}\ \approx\ \log_d n = \frac{\log_2 n}{\log_2 d}, \qquad T_{\text{extract-min}}\ \approx\ d\log_d n = \frac{d}{\log_2 d}\,\log_2 n
Wider nodes make the tree shorter, which helps every operation that climbs, and make each level of a descent more expensive.
ddHeight at n=106n = 10^6insert ≤\leextract-min ≤\led/log⁡2dd/\log_2 d
21919382
31313391.89
41010402
877562.67
1655804
Worst-case comparisons for one million keys. Insertion keeps getting cheaper as dd grows. Extract-min is cheapest at d=3d = 3, because d/ln⁡dd/\ln d is smallest at d=ed = e, and d=4d = 4 ties with d=2d = 2.

The right dd depends on the mix of operations. A workload of II insertions and decrease-keys and XX extract-mins costs about (I+dX)log⁡dn(I + dX)\log_d n comparisons, so the best dd grows with I/XI/X. Dijkstra's algorithm makes up to mm decrease-keys and nn extract-mins, and d≈m/nd \approx m/n gives O(mlog⁡m/nn)O(m\log_{m/n} n) 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.

python
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 = c

Sift-up is unchanged except for the parent, ⌊(i−1)/d⌋\lfloor (i-1)/d \rfloor, and heapify starts at the last internal node, ⌊(n−2)/d⌋\lfloor (n-2)/d \rfloor.

Check your understanding

For large nn and a workload of extract-mins only, which arity minimizes the worst-case number of comparisons?

  1. d=2d = 2
  2. d=3d = 3
  3. d=4d = 4
  4. As large as memory allows
Show the answer

B. d=3d = 3

Extract-min costs about (d/log⁡2d)log⁡2n(d/\log_2 d)\log_2 n comparisons: 2 for d=2d = 2, about 1.89 for d=3d = 3, 2 again for d=4d = 4, and more beyond. The continuous minimum of d/ln⁡dd/\ln d is at d=e≈2.72d = e \approx 2.72.

Saving comparisons on both paths

The lower bound leaves room for about log⁡2n\log_2 n comparisons per insert-plus-extract pair, but a textbook binary heap may spend 3log⁡2n3\log_2 n: log⁡2n\log_2 n up and 2log⁡2n2\log_2 n 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 ⌈log⁡2(h+1)⌉\lceil \log_2(h+1) \rceil comparisons, where hh is the leaf's depth: about log⁡2log⁡2n\log_2\log_2 n, 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 O(log⁡n)O(\log n).

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.

python
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 top

CPython'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 log⁡2log⁡2n\log_2\log_2 n comparisons per insertion, and about log⁡2n\log_2 n 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 log⁡2n\log_2 n lower bound for the pair.

Key takeaways

  • The heights of an nn-node heap add up to n−s2(n)n - s_2(n), the exponent of 2 in n!n!, so bottom-up heapify makes fewer than nn swaps and 2n2n comparisons; its exact worst case is 2n−2s2(n)−e2(n)2n - 2s_2(n) - e_2(n) comparisons. Repeated insertion is Θ(nlog⁡n)\Theta(n\log n) in the worst case, though linear on average.
  • There are n!/∏vsvn!/\prod_v s_v heaps on nn keys, so building one needs about 1.364n1.364n comparisons in the worst case; Li and Reed proved 1.37n+o(n)1.37n + o(n), Gonnet and Munro achieve 1.625n1.625n, and the true constant is open.
  • Every comparison-based priority queue sorts, so insert plus extract-min costs at least log⁡2n−O(1)\log_2 n - O(1) comparisons amortized: one of the two must be logarithmic.
  • A dd-ary heap has height about log⁡dn\log_d n: insert and decrease-key get cheaper as dd grows, extract-min costs about dlog⁡dnd\log_d n 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.

Question 1

Bottom-up heapify runs on 12 keys. At most how many swaps can it make?

  1. 6
  2. 10
  3. 12
  4. 24
Show the answer

B. 10

Swaps are bounded by the total height 12−s2(12)=12−2=1012 - s_2(12) = 12 - 2 = 10. In 0-based terms, indices 3, 4 and 5 have height 1, indices 1 and 2 height 2, and the root height 3: 1+1+1+2+2+3=101+1+1+2+2+3 = 10.

Question 2

How many different min-heaps can be formed from the keys 1, 2, 3, 4, 5?

  1. 24
  2. 40
  3. 120
  4. 8
Show the answer

D. 8

The subtree sizes are 5 (root), 3 (index 1), and 1 for the three leaves, so 5!/(5⋅3)=85!/(5\cdot3) = 8. Key 1 must be at the root, and the three-node subtree must hold its own minimum on top.

Question 3

Why must every comparison-based priority queue spend log⁡2n−O(1)\log_2 n - O(1) comparisons, amortized, on an insert plus an extract-min?

  1. Because a heap of nn keys has height ⌊log⁡2n⌋\lfloor\log_2 n\rfloor
  2. Because nn insertions followed by nn extract-mins sort the keys, which takes ⌈log⁡2n!⌉\lceil\log_2 n!\rceil comparisons
  3. Because extract-min must look at every leaf of the heap
  4. Because each new key must be compared with every key already stored
Show the answer

B. Because nn insertions followed by nn extract-mins sort the keys, which takes ⌈log⁡2n!⌉\lceil\log_2 n!\rceil comparisons

The reduction from sorting holds for any comparison-based structure, heap-shaped or not. Dividing log⁡2n!=nlog⁡2n−1.443n+O(log⁡n)\log_2 n! = n\log_2 n - 1.443n + O(\log n) among nn pairs of operations gives the bound.

Question 4

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?

  1. 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
  2. It uses binary search on the root-to-leaf path
  3. It performs no swaps at all, and swaps are what comparisons count
  4. 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.