What a priority queue promises
A queue hands out elements in arrival order. A priority queue hands out the element with the smallest key next (a min-priority queue), whatever order they arrived in. The operations:
- push(x): add an element.
- peek: look at the smallest element without removing it.
- pop: remove and return the smallest element.
Schedulers (run the most urgent task), simulations (process the earliest event), Dijkstra's shortest paths and Prim's spanning tree (expand the closest vertex), and "top k" queries all need exactly this. A sorted array gives O(1) pop but O(n) push; an unsorted array gives O(1) push but O(n) pop. A binary heap makes both O(log n).
A tree stored in an array
A binary heap is a complete binary tree: every level is full except possibly the last, which fills from the left. Such a tree needs no pointers. Store it level by level in an array, and the links follow from arithmetic:
parent(i) = (i − 1) / 2 (integer division)
left(i) = 2i + 1
right(i) = 2i + 2
Index 0 is the root; indices 1 and 2 are its children; 3 to 6 are the next level; and so on. The lab draws both views at once: the tree on top and the array it really is underneath, with matching index labels. A heap of n elements has ⌊log₂ n⌋ + 1 levels, so 31 elements fill exactly 5 levels.
The heap property
In a min-heap, every parent is less than or equal to each of its children:
items[parent(i)] ≤ items[i] for every i > 0
Follow any path from the root downward and the values never decrease, so the root holds the
minimum. Siblings are not ordered, and the array as a whole is not sorted: [1, 5, 2, 9, 6]
is a valid min-heap. A max-heap is the same with ≥ (used by heap sort).
push: append, then sift up
Appending at index n keeps the tree complete, but the new value may be smaller than its parent. Sift up repairs that: while the element is not at the root and is smaller than its parent, swap it with the parent.
Each swap moves the element one level up, so push makes at most ⌊log₂ n⌋ swaps and comparisons: O(log n). The Push and pop preset pushes 8, 5, 9, 2, 7: watch 2 climb from index 3 to the root in two swaps.
pop: move the last element to the root, then sift down
The minimum is at index 0, but removing it would leave a hole at the top. Instead:
- Remember
items[0](the answer). - Move the last element into index 0 and shrink the array by one. The tree is complete again.
- Sift down the new root: pick the smaller child (the left one on ties); if it is smaller than the element, swap them and continue from the child's index; otherwise stop.
Why the smaller child? It must become the parent of the other child, so it has to be the smaller of the two. Sift down makes at most two comparisons per level and descends at most ⌊log₂ n⌋ levels: O(log n). Peek just reads index 0: O(1).
heapify: O(n), not O(n log n)
Building a heap from n arbitrary values by pushing them one at a time costs O(n log n). Bottom-up heapify does better:
for i = n/2 − 1 down to 0:
siftDown(i)
Indices n/2 and up are leaves, which are already one-element heaps, so only the first half needs work. Going from the last parent back to the root, each sift down merges two heaps (the subtrees) under a new root.
Why only O(n)? Sift down from a node costs at most its height, and most nodes are low. About n/4 nodes have height 1, n/8 have height 2, n/16 height 3, and so on. The total is at most
n · (1/4 + 2/8 + 3/16 + 4/32 + …) = n · 1 = n swaps,
so heapify does fewer than n swaps and, with at most two comparisons per level visited, fewer than 3n comparisons: O(n). The Heapify preset turns
9 4 7 1 8 2 6 3 5 0 into 0 1 2 3 4 7 6 9 5 8 by sifting only the five non-leaf nodes.
Cost summary
| Operation | Binary heap | Note |
|---|---|---|
| peek | O(1) | index 0 |
| push | O(log n) | sift up, at most height swaps |
| pop | O(log n) | sift down, at most 2 comparisons per level |
| heapify n elements | O(n) | bottom-up |
| search for an arbitrary value | O(n) | a heap is not a search structure |
| extra space | O(1) beyond the array |
The bounds are worst case, not amortized, except that a growing array occasionally resizes.
Equal priorities and stability
A heap is not stable: elements with equal keys do not come out in arrival order. If order among
equals matters (first come, first served for equal urgency), make the key unique by adding an
increasing sequence number: compare (priority, sequence) pairs. Python's heapq documentation
recommends exactly this, which also avoids comparing the payload objects themselves.
Language notes
The four standard libraries all provide an array-backed heap, but they disagree on the default direction. This is the single most common bug.
| Language | Type | Default | Max/min the other way | Empty pop / peek |
|---|---|---|---|---|
| C# | PriorityQueue<TElement, TPriority> (.NET 6+) |
min (lowest priority first) | pass a reversed IComparer<TPriority> |
Dequeue/Peek throw InvalidOperationException; TryDequeue/TryPeek return false |
| Python | heapq functions on a list |
min | negate keys; Python 3.14 adds heappush_max, heappop_max, heapify_max |
heappop raises IndexError |
| Java | java.util.PriorityQueue<E> |
min (natural ordering) | new PriorityQueue<>(Comparator.reverseOrder()) |
poll/peek return null; remove/element throw NoSuchElementException |
| C++ | std::priority_queue<T> |
max (with std::less) |
std::priority_queue<T, std::vector<T>, std::greater<>> |
top/pop on an empty queue are undefined behaviour |
More details worth knowing:
- C#. Element and priority are separate:
Enqueue(element, priority). The documentation describes it as an array-backed quaternary (4-ary) min-heap, not binary; the costs are the same in O-notation. There is no decrease-key. Since .NET 9 aRemovemethod can take out a specific element, but it has to find it first, which is O(n); on earlier versions there is no way at all. The usual workaround for both is to enqueue again and skip stale entries when they come out. Equal priorities come out in no particular order. - Python.
heapqis a set of functions over an ordinary list, soheap[0]is the peek.heapifyis O(n);heapreplace(pop then push) andheappushpop(push then pop) do two operations with one sift.nsmallest/nlargestsolve top-k queries. - Java. The iterator and
toStringshow the internal array order, not sorted order.remove(Object)andcontainsare O(n). The class is not thread-safe; usePriorityBlockingQueueacross threads. - C++.
pop()returnsvoid: readtop()first, thenpop(). The container adaptor sits on top ofstd::make_heap,std::push_heapandstd::pop_heap, which you can also call directly on a vector;make_heapmakes at most 3n comparisons.
The teaching implementation
BinaryHeap is a min-heap over a growable array with an optional comparison (pass a reversed one
for a max-heap). Its constructor heapifies initial items bottom-up; Push, Pop and Peek follow
the steps above, and popping or peeking an empty heap is an error (an exception in C#, Python and
Java, std::underflow_error in C++, so the tests can check it). The shared fixture checks the
values returned and the exact heap array after each sequence, so all four languages must make
the same swaps. Each is also compared with its language's own priority queue on 500 random
sequences of operations.
Common mistakes
- Assuming
std::priority_queueis a min-heap. It is a max-heap by default; usestd::greater<>for a min-heap. - Sifting down to the left child always, instead of the smaller child: the heap property breaks.
- Off-by-one parent formula with 0-based arrays: it is
(i − 1) / 2, noti / 2(that is the formula for 1-based arrays, where children are2iand2i + 1). - Treating the heap array as sorted, or iterating a Java
PriorityQueueand expecting order. - Building a heap by n pushes when all the data is already there: O(n log n) instead of O(n).
Worked practice
1. In a heap array of 20 elements, what are the parent and children of index 6?
Answer
Parent (6 − 1) / 2 = 2; children 2·6 + 1 = 13 and 2·6 + 2 = 14, both below 20, so both exist.
2. Pop once from the min-heap [1, 3, 2, 7, 4]. What is the array afterwards?
Answer
Return 1. Move the last element, 4, to the root: [4, 3, 2, 7]. Children of index 0 are 3 and 2;
the smaller is 2 (index 2), and 2 < 4, so swap: [2, 3, 4, 7]. Index 2 has no children, so stop.
3. You need the 10 largest values from a stream of 10 million numbers. Which heap, and how big?
Answer
A min-heap of size 10. Push each number; whenever the heap grows to 11, pop the minimum. The heap always holds the 10 largest seen so far, at O(log 10) per element and O(10) memory. Its root is the smallest of the current top 10, which is exactly the one to evict.
Summary
- A binary heap is a complete binary tree stored level by level in an array: parent
(i − 1) / 2, children2i + 1and2i + 2. - Min-heap property: every parent ≤ its children, so the minimum is at index 0.
- push sifts up and pop sifts down: O(log n). Peek is O(1). Bottom-up heapify is O(n).
- C#, Python and Java default to min-heaps; C++'s
std::priority_queuedefaults to a max-heap.