← Heaps · guided lesson

Heaps & Priority Queues

1 / 19 · story

the story

Binary heap: sift up and sift down

Every tool here exists because something was too slow or broke without it. Here is what.

1964 · J. W. J. Williams

The binary heap arrived in June 1964, inside J. W. J. Williams's Algorithm 232: Heapsort in Communications of the ACM. It keeps a tree in a plain array with a single rule — every parent ≤ its children — so the minimum is always the first element (A[1] in his ALGOL, index 0 in Java). The Java Toolkit chapter's PriorityQueue card tells how this structure became java.util.PriorityQueue in Java 5. This card is about the two moves that make it work: sift up and sift down.

the problem it solved

Taking the smallest item again and again while new items keep arriving — O(log n) per step instead of re-sorting everything.

why it matters: without it

"Give me the next most urgent item" would mean a full scan or a re-sort on every call — O(n) or O(n log n) instead of O(log n).

sources: J. W. J. Williams, Algorithm 232: Heapsort, Communications of the ACM 7(6), 1964 ↗ · OpenJDK 17 source: java.util.PriorityQueue ("represented as a balanced binary heap") ↗

also in this chapter: Building a heap in O(n) (Floyd's heapify) · Heapsort · Top-k with a size-k heap · Two heaps for a running median · K-way merge with a min-heap · Greedy with a heap