What is a heap
A heap is a binary tree with one rule: every node is smaller than both of its children. The rule says nothing about how a node compares to its sibling, its cousin, or anything not directly above or below it.
The rule pins down exactly one thing: the smallest value sits at the root, where you can read it without searching. Where the rest of the values go is left open, and most of this article is about what that buys.
The triage analogy
A hospital emergency department does not keep its waiting room sorted, because the only question ever asked is "who do we see next". So the staff maintain something much cheaper: the most urgent case at the front, and a rough hierarchy behind it where nobody is queued ahead of someone more urgent. When the front patient is taken in, someone from the back is pulled forward and settles to their level. Nobody ever learns whether patient 47 outranks patient 112.
10 is the minimum · but 20 sits a level below 25, and nothing is wrong
Look at that figure once more: 20 is deeper in the tree than 25, and smaller. In a Binary Search Tree that would be a defect. In a heap it's allowed, because the rule only compares a node with its own children.
Min-heap and max-heap
The rule above describes a min-heap: every parent is smaller than its children, so the minimum sits at the root. A max-heap flips the comparison. Every parent is larger than its children, and the root holds the maximum. The shape, the array layout and the operations stay the same, and each < in the code becomes a >. Here are the same seven values arranged as a max-heap:
50 is the maximum · the smallest value, 10, is just one of the leaves
Which one you build depends on the question you keep asking. A timer queue wants the earliest deadline, so it uses a min-heap. A job queue that runs the most urgent job first wants a max-heap. Languages don't agree on a default:
- Go's
container/heaporders by yourLess, so a max-heap is aLessthat returnsa > b. - Python's
heapqis a min-heap. The usual way to get a max-heap was to push negated values, until Python 3.14 addedheappush_max,heappop_maxandheapify_max. - Java's
PriorityQueuekeeps the smallest at the head, and takesCollections.reverseOrder()to keep the largest. - C++'s
priority_queueand Rust'sBinaryHeapare max-heaps by default.
This article uses min-heaps throughout.
The problem a Binary Search Tree couldn't solve
The previous article finished a structure that answers "where is this value" in guaranteed O(log n), keeps everything sorted, and supports range queries. That's far more than you need if your only question is "what is the smallest one right now".
A balanced BST maintains a total ordering: every value's position implies how it compares to every other value. That costs two pointers per node, a rebalancing pass on every write, and a scattered memory layout where each step of a lookup is a cache miss. If all you do is take the minimum and add new values, you pay for a complete ranking and read one entry from it. And the minimum of a BST is its leftmost node, so even reading it is O(log n). A heap gives up almost all of that ordering and still answers "what is the smallest".
Priority Queue is the ADT, heap is the structure
The two names get used interchangeably, but one is an abstract data type and the other is a data structure.
A Priority Queue is an abstract data type. It defines operations and their behaviour, and says nothing about memory: insert(value), extract-min() and peek(). It's the queue from earlier in the series with the FIFO rule replaced: instead of the oldest item, the most urgent one leaves first.
There is no search, no iterate in order and no get the third smallest, and a Priority Queue that can't do those isn't incomplete, because they were never part of the contract. Several concrete structures satisfy it, with very different cost profiles:
| Implementation | insert | extract-min | peek |
|---|---|---|---|
| Unsorted array | O(1) | O(n) | O(n) |
| Sorted array | O(n) | O(1) | O(1) |
| Balanced BST | O(log n) | O(log n) | O(log n) |
| Binary heap | O(log n) | O(log n) | O(1) |
| Fibonacci heap | O(1) | O(log n) | O(1) |
The two arrays are the extremes: one makes insertion free and extraction linear, the other does the reverse. The balanced BST is O(log n) at everything, including the read. The Fibonacci heap has the best bounds on paper, but its constant factors are large enough that almost nothing uses it. The binary heap is logarithmic on both writes and constant on the read, and it does that with a flat array and no pointers.
The invariant, and everything it does not say
The heap invariant is a statement about edges, not about the whole tree. For every node i, value[i] <= value[2i+1] and value[i] <= value[2i+2], and nothing else.
The BST invariant is a statement about entire subtrees: everything left is smaller, everything right is larger, all the way down. It constrains a node against n other values; the heap rule constrains it against two.
That leaves a lot of freedom. Seven distinct values form 80 legal min-heaps. Here are two of them:
this one is the values in ascending order, and sorted input is always already a heap
every slot but the root holds a different value, and the invariant holds just as completely
Only the root matches, because it's the only position the invariant determines. Fix a BST's shape and those seven values have one legal arrangement; a heap has eighty. That freedom is also what keeps writes cheap: an insert or an extract only repairs one path, not a global order.
It's also why you can't read a heap in order. No single pass over the array yields sorted output, because the array doesn't hold that information. Getting it means extracting the minimum repeatedly, which costs O(n log n) and empties the heap. Sorted iteration, range queries and "find the value nearest x" aren't available either.
Complete by construction
The invariant says nothing about which slot a value occupies, only how a slot compares to the two below it, so the heap is free to choose its own shape. It stays a complete binary tree: every level full except possibly the last, which fills left to right.
No code maintains that shape on purpose. It follows from the two operations: insertion appends at the first free position, removal takes the last occupied one, and neither leaves a gap in the middle. A complete tree, as the binary trees article showed, is the case where the array representation wastes no slots:
As a tree
As the slice in memory (h.values)
left := 2*i + 1right := 2*i + 2parent := (i - 1) / 2That article also showed the same representation on a degenerate tree, where 21 nodes in a chain need two million slots. A heap is never degenerate, so it always lands in the case with no waste.
So the tree in the drawing doesn't exist in memory. There are no nodes, no Left or Right fields and no allocations, only one contiguous slice of integers, and the tree is a way of reading the index arithmetic. The tree in the playground below is a view; the array under it is the structure.
Sifting up, and sifting down
Both write operations work the same way: put the value in the only slot that keeps the tree complete, then let it move along a single root-to-leaf path until the invariant holds. Only that one value moves, at most log n levels.
Insert sifts up
Append at the end of the array, the first free slot, then swap with the parent while the new value is smaller. Inserting 5 into the heap above, it lands at index 7 as a child of 40.
the invariant is broken in exactly one place: 5 sits under 40
Now 5 climbs. Smaller than 40, so they swap; smaller than 25, swap; smaller than 10, swap. Three comparisons, three swaps, and it stops at the root.
swapped past 40, then 25, then 10 · 3 comparisons · 3 swaps · 30, 15, 50 and 20 never read
Only one root-to-leaf path was touched, and nothing in the right subtree was even read.
Extract-min sifts down
The minimum is at the root, so reading it is free. Removing it leaves a hole at index 0, and the fix is to move the last element into the root and let it sink. At each level it compares against both children and swaps with the smaller one, stopping when both are larger.
Extracting from the heap we just built: 5 comes off the root, 40 moves up from the end, then sinks past 10 and past 25 to index 3.
5 is gone · 40 now sits above 10, the one place the invariant is broken
At the root, 40 is compared with both children, 10 and 15, and swaps with the smaller; at index 1 it is compared with 25 and 30 and swaps again; at index 3 it has no children left.
4 comparisons · 2 swaps · the heap we started with: insert then extract-min is an exact round trip
Promoting the smaller child looks like the obvious repair, since it's already the next-smallest value and the invariant would hold right away. But it only moves the hole down a level, and repeating that leaves a gap in the middle of the last row. The tree stops being complete and the index arithmetic breaks: 2i+1 only points at a real child if every earlier slot is filled. Promoting the last element costs two extra comparisons per level, and in exchange the array never has a gap.
Representing a heap in memory
There's no node type in this implementation, only a slice and three index functions.
package mainimport "fmt"func main() { h := &MinHeap{} for _, v := range []int{10, 25, 15, 40, 30, 50, 20} { h.Push(v) } fmt.Println(h.values) // [10 25 15 40 30 50 20] h.Push(5) fmt.Println(h.values) // [5 10 15 25 30 50 20 40] min, _ := h.Pop() fmt.Println(min, h.values) // 5 [10 25 15 40 30 50 20] // Heapify does the same in one pass over an unordered slice. g := Heapify([]int{40, 30, 50, 10, 25, 15, 20}) fmt.Println(g.values) // [10 25 15 30 40 50 20] fmt.Println(g.Peek()) // 10 true}package main// MinHeap is a binary min-heap. No node type, no pointer: the tree// is complete by construction, so parent and child are arithmetic.type MinHeap struct { values []int}func parent(i int) int { return (i - 1) / 2 }func left(i int) int { return 2*i + 1 }func right(i int) int { return 2*i + 2 }func (h *MinHeap) Peek() (int, bool) { if len(h.values) == 0 { return 0, false } return h.values[0], true}// Push appends, then walks the value up until its parent is// smaller. The append is why the slice never develops a hole.func (h *MinHeap) Push(value int) { h.values = append(h.values, value) for i := len(h.values) - 1; i > 0; { p := parent(i) if h.values[p] <= h.values[i] { break } h.values[p], h.values[i] = h.values[i], h.values[p] i = p }}// Pop removes the root, moves the last element into it, and walks// that value down. Promoting a child would leave a hole midway.func (h *MinHeap) Pop() (int, bool) { if len(h.values) == 0 { return 0, false } min := h.values[0] last := len(h.values) - 1 h.values[0] = h.values[last] h.values = h.values[:last] h.siftDown(0) return min, true}func (h *MinHeap) siftDown(i int) { for { smallest := i l, r := left(i), right(i) if l < len(h.values) && h.values[l] < h.values[smallest] { smallest = l } if r < len(h.values) && h.values[r] < h.values[smallest] { smallest = r } if smallest == i { return } h.values[i], h.values[smallest] = h.values[smallest], h.values[i] i = smallest }}// Heapify rearranges a slice into a heap, bottom-up and in place.// Starting at the last node with a child skips every leaf (half the// slice), which is why this is O(n).func Heapify(values []int) *MinHeap { h := &MinHeap{values: values} for i := parent(len(values) - 1); i >= 0; i-- { h.siftDown(i) } return h}There's no Node struct, no nil check, no recursion and no allocation beyond the slice growing; Push and Pop are each one loop over an index. It's the most compact structure in the series, because the invariant is weak enough that a node's position can be computed instead of stored.
Try it yourself
The array is the structure and the tree is a view of it, so the playground shows both and moves them together, one comparison or one swap per step. Insert a value and watch it land in the dashed slot at the end, then get compared with its parent and climb; extract and watch the last element get promoted to the root and sink, compared with both children at every level. The result counts the comparisons and the swaps.
the slice, which is the structure: the tree above only draws it
Keyboard and mouse
- Space
- play or pause
- ←→
- previous or next step
- HomeEnd
- start or end of the run
- <>
- slower or faster
- M
- sound on or off
- F
- fullscreen
- R
- reset
- Space+drag
- move the canvas
- Ctrl+scroll
- zoom
- every step of the next run shows up here
Insert a value smaller than everything present and it travels to the root, one comparison and one swap per level, along the only path the structure touched. Then insert a large value and watch it stop after a single comparison. The next section depends on that difference.
Building a heap from an array
Suppose you already have n values and want a heap. There are two ways, and the gap between them is one of the most quoted facts about heaps, usually without the qualifier it needs.
Insert them one at a time, at O(log n) each, for O(n log n). Or put them all in the array as they are and sift down from the last internal node back to the root, which is O(n). Sifting down is cheap where nodes are numerous: half of all nodes are leaves and can't move, a quarter can move one level, and only the root can move log n. That sum converges to a constant times n.
- O(n)
- O(n log n)
As a tree
As the slice in memory (h.values)
the four greyed leaves need no work · the build starts at index 2 and walks back to 0
Three sift-downs turn that into [10, 25, 15, 30, 40, 50, 20], with every leaf skipped, which on a large heap is half the array. The textbook advice is to use the bottom-up build, and it's right, though the reason usually given for it needs a qualifier.
What measuring says
I instrumented both builds to count comparisons, on random input and on descending input. Descending is the adversarial case for insertion, since every arriving value beats everything already in the heap and climbs to the root.
| n | Bottom-up, random | Bottom-up, descending | Insertion, random | Insertion, descending | log₂ n |
|---|---|---|---|---|---|
| 64 | 1.73 | 1.81 | 1.91 | 4.13 | 6 |
| 1,024 | 1.85 | 1.98 | 2.23 | 8.01 | 10 |
| 16,384 | 1.88 | 2.00 | 2.27 | 12.00 | 14 |
The numbers are comparisons per element. Each column is one build on one kind of input, so read down a column to see how it grows with n.
The bottom-up build is flat: 1.7 to 2.0 per element across a 256× range of sizes, random or adversarial. That constant cost per element is how O(n) shows up when you measure it.
The insertion build is where the usual explanation misleads. On random input it costs 2.27 per element at n = 16,384, against a log₂ n of 14, which is barely worse than the bottom-up build and shows no n log n growth. The reason is visible in the playground: a randomly chosen value is usually larger than its parent, so it stops after one comparison, and the log n per insert is a worst case that random data almost never reaches. On descending input it costs 12.00, within two of log₂ n. That's where the n log n shows up, and only when the input arrives sorted the wrong way.
Heapsort
Build a heap in O(n), then extract the minimum n times at O(log n) each. The output comes out sorted, for O(n log n) total.
Heapsort needs no extra memory. Extraction shrinks the heap by one slot at the end of the array, and that slot is exactly where the extracted value goes, so the array fills with sorted values from the back while the heap shrinks toward the front. That's O(1) extra space, which mergesort can't offer and quicksort only gets with care, and an O(n log n) worst case on any input.
Placed that way, a min-heap leaves the array in descending order, with the smallest value at the back. For ascending order, heapsort builds a max-heap instead: each extraction moves the current maximum to the end. That's the version Go's sort package and C++'s std::sort_heap use.
Almost nothing uses heapsort as its primary sort anyway, for two reasons.
It is not stable. Two equal values can come out in the opposite order to the one they went in, because the sift swaps them across the array with no regard for where they started. If you sort records by one field and expect ties to keep their previous order, heapsort silently breaks that.
Its memory access pattern is hostile. Every sift down jumps from index i to 2i+1, so the further into a large array you go the further apart consecutive accesses are. Quicksort scans linearly, which suits the cache well enough that it wins in practice despite its O(n²) worst case.
Most standard libraries ship introsort instead: quicksort, switching to heapsort if the recursion passes 2 log n levels. Heapsort is probably in your language's sort function, but only as the fallback for inputs that would make quicksort quadratic.
Common operations and their costs
| Operation | Binary heap | Balanced BST |
|---|---|---|
| Peek at the minimum | ||
| Insert | ||
| Extract the minimum | ||
| Build from n values | ||
| Search an arbitrary value | ||
| Read all values in order |
The top four rows are what heaps are for; the bottom two are what they give up. The fourth and the sixth rows come from the same fact: a heap builds in linear time because it never reaches sorted order, and for the same reason getting sorted output out of it costs O(n log n).
Heaps in the real world
Schedulers and timers. Go's own runtime keeps each processor's pending timers in a min-heap, so "which fires next" is a constant-time read. It uses a 4-ary heap rather than a binary one: with four children per node the tree is shallower, and a sift down does more comparisons at fewer levels, which suits a cache. Python's asyncio schedules its callbacks with heapq. Cron, job queues, rate limiters, discrete-event simulations and a game engine's timed events have the same shape: many pending items, and the program keeps asking which one comes next.
Top-k without sorting. To find the 10 largest values in a stream of a billion, keep a min-heap of size 10: for each new value, compare against the root, and if it is larger replace the root and sift down. You end up holding the top 10 in O(n log k) time and O(k) space, without ever storing the stream.
Using a min-heap to track the largest values sounds backwards, but the root is the smallest of your current ten, which is exactly the one a larger value should evict.
Shortest paths. Dijkstra's algorithm and A* both work by repeatedly taking the closest unvisited node, which is a priority queue by definition. This is the most common place a working programmer uses a heap deliberately.
Your language already ships one. Go's container/heap supplies the sift logic once you provide five methods: Len, Less and Swap, plus a Push and Pop that the package calls on your slice. Those aren't the ones you call yourself (you call heap.Push and heap.Pop), and mixing them up is the usual mistake. Python's heapq works over a plain list, and Rust's BinaryHeap, a max-heap, becomes a min-heap if you wrap the values in Reverse.
When Heaps fall short
There is no search. Finding an arbitrary value is O(n), because the invariant offers no direction to go at any node. Needing "is x in here" as well as "what is the minimum" means a second index alongside the heap.
Updating an arbitrary element needs help. Decrease-key (lowering a value's priority) is what Dijkstra actually wants, and it is O(log n) if you already know the element's index. Finding that index is the O(n) search above. Real implementations keep a separate map from value to index and update it on every swap, which is fiddly and the most common source of bugs in hand-written heaps.
Only one end is fast. A min-heap answers "what is the smallest" in O(1) and "what is the largest" in O(n), because the maximum is somewhere among the leaves. Needing both means a min-max heap or two heaps. The usual way to keep a running median holds the lower half of the values in a max-heap and the upper half in a min-heap, so the median is always at one of the two roots.
No ordering, no ranges. Everything the previous two articles offered (sorted iteration, BETWEEN, successor and predecessor) is gone. If you need those and fast minimum access, a balanced BST gives both.
Merging two heaps is slow. Combining two binary heaps of size n means rebuilding, at O(n); binomial, pairing and leftist heaps are designed for it and merge in O(log n).
Summary
- The invariant is only parent against child: nothing between siblings or between subtrees, which is why seven values form 80 legal heaps and only the root is pinned down
- Min-heap or max-heap: the same structure with the comparison flipped, holding the minimum or the maximum at the root
- Complete by construction: insert fills the first free slot and extract takes the last one, so the tree never has a gap and the array representation wastes nothing
- No pointers: one contiguous slice, with
2i+1,2i+2and(i−1)/2replacing every pointer - Insert sifts up, extract sifts down: one value moves along one root-to-leaf path, at most
log nlevels - Extract promotes the last element, not the smaller child, because that's the only choice that leaves no hole
- Bottom-up building is
O(n): under 2 comparisons per element at every size and input order measured, while insertion reacheslog nper element only on adversarial input - Heapsort is in-place with an
O(n log n)worst case, and not stable, which is why it ships as introsort's fallback rather than as the default sort