Building a Heap in Linear Time
There are two obvious ways to turn an array of values into a max-heap. One is to insert the values one by one, each sifting up from the bottom. The other is to sift down every internal node, starting from the last one and working back to the root. Both are correct, and both look like " operations of cost ", so both seem to cost . The first one really does. The second one costs only , and the reason is a short sum that is worth knowing by heart.
This lesson builds on Sift-Down and Why It Works and the height facts from Binary Heaps and the Heap Property.
The bottom-up algorithm
The leaves, positions to , are already one-element heaps. Every other node can be fixed by sift-down as soon as both of its children are roots of heaps. Processing positions from down to guarantees exactly that, because children have larger indices than their parents.
BUILD-MAX-HEAP(a)
1 n = length of a
2 for i = floor(n/2) - 1 down to 0
3 SIFT-DOWN(a, i, n)The animation is heapsort, whose first phase is this procedure; it ends at "Max-heap built". On this input position 3 (value 7) is already larger than its children, position 2 swaps once, position 1 is fine, and the root sinks three levels.
def sift_down(a, i, size):
while True:
l, r = 2 * i + 1, 2 * i + 2
largest = i
if l < size and a[l] > a[largest]: largest = l
if r < size and a[r] > a[largest]: largest = r
if largest == i:
return
print(f" swap {a[i]} (pos {i}) with larger child {a[largest]} (pos {largest})")
a[i], a[largest] = a[largest], a[i]
i = largest
def build_max_heap(a):
for i in range(len(a) // 2 - 1, -1, -1):
print(f" sift-down at position {i} (value {a[i]})")
sift_down(a, i, len(a))
a = [2, 9, 4, 7, 1, 8, 5, 3, 6]
print("input:", a)
build_max_heap(a)
print("heap: ", a)input: [2, 9, 4, 7, 1, 8, 5, 3, 6]
sift-down at position 3 (value 7)
sift-down at position 2 (value 4)
swap 4 (pos 2) with larger child 8 (pos 5)
sift-down at position 1 (value 9)
sift-down at position 0 (value 2)
swap 2 (pos 0) with larger child 9 (pos 1)
swap 2 (pos 1) with larger child 7 (pos 3)
swap 2 (pos 3) with larger child 6 (pos 8)
heap: [9, 7, 8, 6, 1, 4, 5, 3, 2]
Each "swap" line is one "Swap parent and child" frame of the animation.
In C++
#include <algorithm>
#include <cstdio>
#include <vector>
void sift_down(std::vector<int>& a, int i, int size) {
for (;;) {
int l = 2 * i + 1, r = 2 * i + 2, largest = i;
if (l < size && a[l] > a[largest]) largest = l;
if (r < size && a[r] > a[largest]) largest = r;
if (largest == i) return;
std::swap(a[i], a[largest]);
i = largest;
}
}
void build_max_heap(std::vector<int>& a) {
int n = static_cast<int>(a.size());
for (int i = n / 2 - 1; i >= 0; --i) sift_down(a, i, n);
}
int main() {
std::vector<int> a = {2, 9, 4, 7, 1, 8, 5, 3, 6};
build_max_heap(a);
std::printf("heap:");
for (int x : a) std::printf(" %d", x);
std::printf("\nstd::is_heap agrees: %s\n", std::is_heap(a.begin(), a.end()) ? "yes" : "no");
}heap: 9 7 8 6 1 4 5 3 2
std::is_heap agrees: yes
Correctness
Invariant. At the start of each iteration of the loop in line 2, every position is the root of a max-heap.
- Initialization. Before the first iteration , so the positions in question are to : exactly the leaves, and a single node is a heap.
- Maintenance. The children of are and , both larger than , so by the invariant they are roots of heaps (or do not exist). That is the precondition of sift-down, which therefore makes the root of a heap. Sift-down only moves values inside the subtree of , so the heaps rooted at other positions larger than are untouched. Decreasing restores the invariant.
- Termination. The loop ends with , and the invariant says position is the root of a max-heap: the whole array is a heap.
Why it costs only O(n)
A sift-down from a node of height costs . By the heap-property lesson there are at most nodes of height , and the heights go up to . So, for some constant ,
The key is the series
which follows from differentiating the geometric series: for , and gives . The intuition: half the nodes are leaves and cost nothing, a quarter cost one level, an eighth two levels. The expensive nodes near the top are few, and their count halves faster than their cost grows.
There is even an exact formula. The total height of all nodes, which bounds the number of swaps, is
where is the number of 1-bits in the binary representation of . Since sift-down makes at most two comparisons per level, building a heap needs fewer than swaps and fewer than comparisons, for every input. The program checks the formula and measures the two strategies on sorted input, the worst case for sifting up.
def heights_sum(n):
h = [0] * n
for i in range(n - 1, -1, -1):
for c in (2 * i + 1, 2 * i + 2):
if c < n:
h[i] = max(h[i], h[c] + 1)
return sum(h)
print("total height = n - (1-bits of n) for n = 1..1000:",
all(heights_sum(n) == n - bin(n).count("1") for n in range(1, 1001)))
def bottom_up(a):
comps = swaps = 0
n = len(a)
for i in range(n // 2 - 1, -1, -1):
while True:
l, r, largest = 2 * i + 1, 2 * i + 2, i
if l < n:
comps += 1
if a[l] > a[largest]: largest = l
if r < n:
comps += 1
if a[r] > a[largest]: largest = r
if largest == i: break
a[i], a[largest] = a[largest], a[i]; swaps += 1
i = largest
return comps, swaps
def by_insertion(a):
heap, comps, swaps = [], 0, 0
for x in a:
heap.append(x)
i = len(heap) - 1
while i > 0:
comps += 1
p = (i - 1) // 2
if heap[p] >= heap[i]: break
heap[p], heap[i] = heap[i], heap[p]; swaps += 1
i = p
return comps, swaps
for n in [1000, 4000, 16000]:
c1, s1 = bottom_up(list(range(n)))
c2, s2 = by_insertion(list(range(n)))
print(f"n = {n:>6}: bottom-up {c1:>7} comparisons {s1:>6} swaps | one push at a time {c2:>7} comparisons {s2:>7} swaps")total height = n - (1-bits of n) for n = 1..1000: True
n = 1000: bottom-up 1982 comparisons 992 swaps | one push at a time 7987 comparisons 7987 swaps
n = 4000: bottom-up 7978 comparisons 3990 swaps | one push at a time 39917 comparisons 39917 swaps
n = 16000: bottom-up 31974 comparisons 15988 swaps | one push at a time 191631 comparisons 191631 swaps
On sorted input each pushed value is the largest so far and climbs all the way to the root, so the -th value (counting from 1) makes exactly swaps, and ; for that sum is the 7987 in the first row. Bottom-up construction does fewer than swaps on the same input. The asymmetry is the point: a node near the bottom has a long way to climb but a short way to sink. Most nodes are near the bottom, so the method that charges each node its distance to the bottom (sift-down) wins.
In practice: Python's
heapq.heapifyand C++'sstd::make_heapboth build bottom-up in . If you have all the values up front, call them instead of pushing one by one.
When you only want the k largest
Linear-time construction makes "the largest of values" cost : build a heap in and extract the maximum times. Another way is to keep a min-heap of size while scanning, , which needs only memory, the usual choice for a stream. Selection in Randomized Quickselect finds the -th largest itself in expected . The practice problem K-th Largest can be solved all three ways.
Test yourself
Why does BUILD-MAX-HEAP process the positions from down to and not upward?
- Upward would also work, it is only a convention
- Sift-down at needs both children to be roots of heaps already, and children have larger indices
- To make the result stable
- Because the leaves are at the front of the array
What is , the series behind the linear bound?
- 1
- 2
- It diverges
How many swaps can bottom-up heap construction make at most on values?
- 15
- 16
- 64
- minus one
Building a max-heap by inserting sorted input one at a time costs...
- , like bottom-up construction
- , because every new value climbs to the root