← The Ledger
Vol. I, No. 13 · Heap Structures

The Binary Heap

A complete binary tree stored in an array, with one comparison invariant per edge.

Written by Khushal Agrawal

loading…

Complete Tree In An Array

A binary heap is a complete binary tree: every level is full except the last, which fills from the left. Completeness makes the shape a function of the element count alone, so the tree needs no pointers — the nodes are written into an array in level order.

parent(i) = (i - 1) / 2
left(i)   = 2*i + 1
right(i)  = 2*i + 2

Navigation is arithmetic on an index. A heap of n elements occupies exactly n slots with no per-node overhead, and its height is ⌊log₂ n⌋.

Heap Property

In a min-heap every node holds a key no greater than the keys of its children. The root therefore holds the minimum, and find-min reads one array slot in O(1) time. A max-heap reverses the comparison; the two are the same structure under an inverted order.

The property is a partial order, not a total one. Siblings are unrelated, subtrees at the same depth are unrelated, and an array scan does not produce sorted output. Maintaining this weaker order is what allows updates in logarithmic time; a fully sorted array would need linear work per insertion. The priority queue interface asks for nothing stronger.

Sift Up

Insertion appends the key at index n, the first free slot, which preserves completeness but may break the heap property on the single edge to its parent. Sift up walks that edge upward until the parent is smaller or the key reaches the root.

void sift_up(int i) {
    key_t x = a[i];
    while (i > 0) {
        int p = (i - 1) / 2;
        if (a[p] <= x) break;
        a[i] = a[p];        // shift the parent down into the hole
        i = p;
    }
    a[i] = x;               // one write, at the final position
}

Only ancestors are examined, so the cost is O(log n) with one comparison per level. Carrying the key in x and shifting parents into the hole halves the memory traffic of a swap chain. For random insertion order the expected number of moves is O(1), because half the nodes are leaves.

Sift Down

extract-min removes the root and refills the hole without breaking completeness: move the last element into the root, shrink the length, then sift down against the smaller child. Swapping with the larger child would place a key above its sibling and break the property immediately.

void sift_down(int i, int n) {
    key_t x = a[i];
    for (;;) {
        int c = 2*i + 1;
        if (c >= n) break;
        if (c + 1 < n && a[c + 1] < a[c]) c++;   // comparison 1: pick child
        if (x <= a[c]) break;                    // comparison 2: test key
        a[i] = a[c];
        i = c;
    }
    a[i] = x;
}

Two comparisons per level against sift up's one — the asymmetry that every heap variant in this chapter is reacting to. Deleting an arbitrary index uses the same move-the-last-element trick, then sifts in whichever direction the property broke.

Linear-Time Heapify

Building a heap by n successive insertions costs O(n log n). Building it in place costs O(n), and the code is one loop.

for (int i = n/2 - 1; i >= 0; i--)
    sift_down(i, n);

The second half of the array is leaves, and a leaf is already a valid one-element heap, so the loop starts at the last internal node. Each call assumes both subtrees below i are already heaps, which the reverse index order guarantees. The method is Floyd's 1964 treesort3; the next card is why the total is linear rather than n log n.

Why Heapify Is Linear

The bound follows from where the nodes are. Most of them sit near the bottom, and a node near the bottom has almost nowhere to sift.

nodes at height h   <=  ceil(n / 2^(h+1))
cost of one sift    =   O(h)

total  <=  n * sum over h of  h / 2^(h+1)
        =  n * 1                      // the series converges to 1
        =  O(n)

Half the nodes are leaves and sift zero levels; a quarter sift at most one; only the root can sift log₂ n. The expensive nodes are rare enough that the weighted sum stays constant, which is why construction is linear while n insertions are not.

Comparison Counts

A standard extract-min performs about 2 log₂ n comparisons. The key it sifts came from the bottom of the heap, so it almost always travels the whole way back down — the early exit rarely fires.

// bottom-up: descend to a leaf first, one comparison per level
int c = i;
while (2*c + 1 < n) {
    int j = 2*c + 1;
    if (j + 1 < n && a[j + 1] < a[j]) j++;
    c = j;
}
while (a[c] > x) c = (c - 1) / 2;   // then walk back to the insert point

Wegener's 1993 bottom-up heapsort drops the second comparison by descending blindly, then climbing back. That is roughly log₂ n + O(1) comparisons per extraction on typical input. When comparisons are expensive — long strings, tuple comparators, database keys — the halving is what the profile shows.

d-ary Heaps

Nothing requires two children. A d-ary heap gives each node d children, and the index arithmetic generalises directly.

parent(i)   = (i - 1) / d
child(i, j) = d*i + 1 + j      // j = 0 .. d-1

Height falls to log_d n, so sift up — and therefore insertion and decrease-key — gets cheaper by a factor of log d. Sift down gets more expensive: each level needs d − 1 comparisons to find the smallest child, giving O(d log_d n). The trade favours update-heavy workloads such as Dijkstra's algorithm. The d children are contiguous, so one level of a four-ary heap often occupies a single cache line, which is why d = 4 is the common choice.

Heapsort

Heapsort is heapify plus n extractions, done in place by moving the extracted maximum into the slot the heap just vacated.

for (int i = n/2 - 1; i >= 0; i--) sift_down(i, n);   // max-heap, O(n)

for (int end = n - 1; end > 0; end--) {
    swap(a[0], a[end]);      // the max takes its final position
    sift_down(0, end);       // restore over the shrinking prefix
}

The result is sorted ascending with O(1) auxiliary memory and an O(n log n) worst case whatever the input. It is nevertheless slower than quicksort on most real inputs: sift down jumps between positions that grow geometrically far apart, defeating prefetch, and the child-selection branch is hard to predict. It is also not stable.

Decrease-Key And Index Maps

Dijkstra's and Prim's algorithms need to lower the key of an element already queued. A plain heap cannot find it — array order carries no information about which slot holds which item — so locating it costs O(n). An indexed heap keeps a map from identity to slot and maintains it on every move.

void move(int from, int to) {
    a[to]  = a[from];
    id[to] = id[from];
    pos[id[to]] = to;          // identity -> slot, kept in sync
}

void decrease_key(item_t v, key_t k) {
    int i = pos[v];            // O(1) instead of O(n)
    a[i] = k;
    sift_up(i);                // key only ever decreases
}

The map costs one slot per item and a write on every move inside both sifts. Merging two binary heaps has no comparable fix: it costs O(n), which is what the binomial heap exists to address.

Lazy Deletion

Most shortest-path code skips the index map entirely. Rather than updating an entry in place, it pushes a second entry with the improved key and discards stale ones as they surface.

push(heap, (new_dist, v));         // no update, just another entry
...
(d, v) = pop(heap);
if (d > dist[v]) continue;         // stale: a better entry already ran

The check is one comparison against the item's best known distance, and it is correct because a stale entry always carries a larger key than the one that superseded it. The cost is that the heap holds up to O(m) entries for m edges rather than O(n), trading memory for the bookkeeping an indexed heap would need on every sift.

Memory And Cache Behaviour

The array layout is the binary heap's practical advantage over every pointer-based competitor. There are no child pointers, no parent pointers, and no per-node allocation: n keys occupy an array of n keys. A pointer-based heap on a 64-bit machine typically adds 24 to 32 bytes of links and marks per node, plus allocator headers.

Locality is uneven. The top of the heap stays resident in cache and is touched by every operation, while the lower levels stride across memory in steps that double each level. Once the heap exceeds cache, a sift down costs roughly one cache miss per level below the resident prefix. Increasing the arity or blocking the layout into cache-line-sized subtrees reduces that miss count without changing the asymptotics.

Engineering Trade-offs

A binary heap gives O(1) find-min, O(log n) insert and extract-min, O(n) construction, and zero space overhead beyond the array, with implementations short enough to audit in one screen. For a bounded working set with no merge requirement, nothing else in the heap family is faster in wall-clock terms.

What it does not give: O(1) merge, O(1) decrease-key, cheap search for an arbitrary key, ordered iteration, or stable ordering among equal keys. It also invalidates positions on every operation, so external references need the index map. Workloads that meld queues constantly want a pairing heap; workloads that need ordered iteration want a search tree such as an AVL tree, not a heap at all.

Applications

Go's runtime keeps pending timers in a four-ary min-heap in runtime/time.go, ordered by firing time, with siftupTimer and siftdownTimer maintaining it as timers are added and cancelled; the scheduler reads the root to learn when it must next wake. CPython's asyncio event loop does the same job with a binary heap — BaseEventLoop holds TimerHandle objects in a heapq list keyed by deadline.

Storage engines merge sorted runs with them: RocksDB's MergingIterator holds one child iterator per memtable and SST file in a heap ordered by current key, presenting many LSM tree levels as one sorted stream, and PostgreSQL's tuplesort.c merges external run tapes the same way. The GNU C++ library's std::sort is introsort: quicksort until recursion depth passes 2 log₂ n, then heapsort, which is what converts quicksort's quadratic worst case into a guaranteed bound.

Summary

A binary heap stores a complete binary tree in an array and maintains the single invariant that no child precedes its parent. Insertion sifts up, extraction moves the last element to the root and sifts down, and bottom-up construction over the internal nodes builds a heap from an unordered array in O(n) time.

Find-min is O(1), insertion and extraction are O(log n) worst-case, and space is exactly the array. The costs are an O(n) merge, a decrease-key that needs a side index, poor locality in the lower levels, and no ordered traversal. Heaps that improve on the merge and decrease-key bounds pay for it with pointers and per-node fields.

The Binary Heap: A complete binary tree stored in an array, with one comparison invariant per edge
The Binary Heap — A complete binary tree stored in an array, with one comparison invariant per edge.

Sources & further reading

Every claim in this chapter traces to a primary source. Peer-reviewed papers are linked by DOI.

Primary sources

  1. Williams, J. W. J. (1964). Algorithm 232: Heapsort. Communications of the ACM, 7(6), 347–348. doi.org/10.1145/512274.512284
  2. Floyd, R. W. (1964). Algorithm 245: Treesort 3. Communications of the ACM, 7(12), 701. doi.org/10.1145/355588.365103
  3. Wegener, I. (1993). Bottom-up heapsort, a new variant of heapsort beating, on an average, quicksort. Theoretical Computer Science, 118(1), 81–98. doi.org/10.1016/0304-3975(93)90364-Y
  4. Johnson, D. B. (1975). Priority queues with update and finding minimum spanning trees. Information Processing Letters, 4(3), 53–57. doi.org/10.1016/0020-0190(75)90001-0

Applications and implementations

  1. The Go Programming Language. src/runtime/time.go — four-ary timer heap. github.com/golang/go/blob/master/src/runtime/time.go
  2. Python Software Foundation. Lib/asyncio/base_events.py — scheduled callbacks in a heapq. github.com/python/cpython/blob/main/Lib/asyncio/base_events.py
  3. Facebook. RocksDB: table/merging_iterator.cc. github.com/facebook/rocksdb/blob/main/table/merging_iterator.cc
  4. PostgreSQL Global Development Group. src/backend/utils/sort/tuplesort.c. github.com/postgres/postgres/blob/master/src/backend/utils/sort/tuplesort.c
  5. Musser, D. R. (1997). Introspective sorting and selection algorithms. Software: Practice and Experience, 27(8), 983–993. doi.org/10.1002/(SICI)1097-024X(199708)27:8%3C983::AID-SPE117%3E3.0.CO;2-%23

Enjoyed this chapter? Support The Ledger.