How a heap always knows the smallest
A priority queue answers "what is the smallest?" in constant time and still accepts new items in logarithmic time. The trick is an ordinary array read as a tree, repaired with one walk up or down after every change.
01 You keep needing the smallest
A job scheduler runs the most urgent job next. A game loop handles the earliest timer next. A route finder expands the nearest place next. Each one asks the same question over and over: what is the smallest item right now? And between questions, items keep arriving and leaving.
The two obvious answers each make one operation slow. A heap makes both cheap by keeping only a little order: enough to know the smallest, and no more.
append, but every "what is smallest?" scans the whole list.02 An array that is secretly a tree
A binary heap is a binary tree with two rules. Shape: every level is full except possibly the last, which fills from the left. Order: in a min-heap, every parent is less than or equal to its children. Nothing is said about left versus right, or about cousins.
The shape rule means the tree never has gaps, so it packs into an array with no wasted slots and no pointers. The root is [0], then its two children, then their four, row by row.
Row by row, left to right, the tree reads 1, 3 2, 5 4 8: exactly the array. There are no pointers; the index is the link.
| From slot i | Formula | Example, i = 1 |
|---|---|---|
| Parent | (i - 1) // 2 | 0 |
| Left child | 2 * i + 1 | 3 |
| Right child | 2 * i + 2 | 4 |
Because the tree is always this compact, its height is about log₂ n. Six items need three levels; a million need twenty. Every operation below walks at most one root-to-leaf path, so that height is the whole cost.
03 Push: append, then sift up
To push, put the new value in the next free slot: the end of the array. That keeps the shape. It may break the order, so compare it with its parent and swap while the parent is bigger. This is sift up.
- just appended
- parent compared
- moved up by a swap
The heap is empty: an empty array, and so no tree.
Each swap moves the new value one level up, and it stops as soon as the parent is not bigger. The worst case is a new minimum, which climbs all the way to the root: about log₂ n swaps.
04 Pop: move the last leaf up, sift down
The smallest value is always at [0]. Taking it out leaves a hole at the top. Filling it with a child would leave a gap lower down, so instead take the last item, which can leave without breaking the shape, and put it in the root. Then push it down, swapping with its smaller child, until neither child is smaller. This is sift down.
- value sifting down
- child compared
- settled
- just popped
Start from the heap the pushes built. The smallest value is at [0], so reading it is free. Removing it is the work.
Sift down does two comparisons per level, to find the smaller child, so a pop costs about 2 log₂ n comparisons. Popping everything one by one gives the values in sorted order: that is heapsort.
05 Write it once, then use the library
The two functions are short. The only subtle line is choosing the smaller child in pop.
That is the real output of python3 main.py (Python 3.14), and it matches the traces. In practice, use the standard library. Python's heapq works on a plain list in the same layout and gives the same array here:
CPython's heappop sifts down a little differently (it pushes the hole to a leaf first, then sifts up), so on other inputs its array can differ from the hand-written one. Both are valid heaps.
| Language | Type | Default order |
|---|---|---|
| Python | heapq functions on a list | Min. Python 3.14 adds heappush_max and friends; before that, push negated values. |
| Java | PriorityQueue | Min, by natural order or a Comparator. |
| C++ | std::priority_queue | Max. Pass std::greater for a min-heap. |
06 What each operation costs
| Operation | Cost | Why |
|---|---|---|
| Peek at the smallest | O(1) | It is always at [0]. |
| Push | O(log n) | One sift up along one path. |
| Pop the smallest | O(log n) | One sift down along one path. |
| Build from n items (heapify) | O(n) | Sift down from the last parent back to the root; most nodes are near the bottom and move little. |
| Find or remove any other value | O(n) | The order rule says nothing about where a value is, so you scan. |
The heap's favourite trick is top k. To find the 2nd largest of [3, 2, 1, 5, 6, 4], keep a min-heap of at most 2 items. Push each number; when the heap grows past 2, pop its smallest. What survives are the 2 largest, and the root is the smaller of them.
Each step works on a heap of size k, not n, so the whole pass is O(n log k) and holds only k items. That is how a leaderboard keeps a live top 100 from a stream of millions of scores.
07 When it bites
print(h) # [1, 3, 2, 5, 4, 8]Treating the array as sortedOnly h[0] is guaranteed. The second smallest is h[1] or h[2], and the last slot is not the largest. To read items in order, pop them.std::priority_queue<int> pq;Assuming every library is a min-heapC++ gives a max-heap by default, Python a min-heap. Check before you port a solution, or the top is the wrong end.heappush(h, (priority, task_dict))Ties compare the next fieldTuples compare element by element. Two equal priorities make Python compare the dicts and raise TypeError. Put a counter in between: (priority, n, task).h[3] = 0 # lower a priority in placeChanging a value inside the heapThe order rule is now broken and nothing repairs it. Push a new entry and skip the old one when it comes out, or use a structure with a decrease-key operation.if x in h:Searching a heapMembership is a linear scan. If you also need lookups, keep a set or dict beside the heap.