Heaps and Priority Queues
A heap is a complete binary tree, stored in an array, where every parent beats its children. That one local rule keeps the minimum (or maximum) at the root, ready in O(1), and lets insert and extract fix the order along a single path in O(log n).
Min Heap and Max Heap
A binary heap is a binary tree with two rules. Shape: it is complete, every level 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, so the smallest value is at the root; in a max heap every parent is greater than or equal to its children, so the largest is at the root.
The order rule is local. It compares each node only with its own children and says nothing about siblings or cousins. A heap is therefore only partly ordered: [2, 5, 3, 9, 7, 8, 6] is a valid min heap, though it is far from sorted.
That weak rule is the point. Keeping everything sorted after each change is expensive; keeping only parent-child order means fixing one path from root to leaf, O(log n). The price is that a heap answers one question quickly, "what is the smallest (or largest)?", and everything else takes a full scan.
- Min heap: parent ≤ children, minimum at the root
- Max heap: parent ≥ children, maximum at the root
- Complete shape keeps the height at ⌊log₂ n⌋
- Siblings are unordered; a heap is not sorted
Stored as an Array
Because the tree is complete, it has no gaps, so the heap data structure is stored as a plain array, level by level, with no pointers. With the root at index 0, the children of index i are at 2i + 1 and 2i + 2, and its parent is at ⌊(i − 1) / 2⌋. Some books start at index 1, giving 2i, 2i + 1 and ⌊i / 2⌋; pick one and do not mix them.
The array layout saves the two child pointers per node, needs no allocation per node, and keeps values side by side, which is kind to the CPU cache. It only works because of the shape rule: a tree with holes would leave unused gaps in the array and break the index arithmetic.
- Children of i: 2i + 1 and 2i + 2; parent: ⌊(i − 1) / 2⌋
- No pointers, one block of memory
- Only possible because the tree is complete
Insert and Extract
Each change is made in the one place that keeps the tree complete, and then the order is repaired along one path.
Insert appends the value at the end of the array. It may be smaller than its parent (in a min heap), so it sifts up: swap with the parent while it is smaller, stop at the root or when the parent is no larger. A new value at the bottom can only be too small for its spot, so it can only move up.
Extract-min takes the root. To avoid a hole, move the last value into the root and shrink the array by one. That value is now probably too large, so it sifts down: compare it with both children and swap with the smaller, until both children are larger or it reaches a leaf. Swapping with the first child that happens to be smaller is a classic bug: the larger of the two children ends up above the smaller one, and the heap returns wrong answers without crashing.
Both operations follow a single root-to-leaf path, so both are O(log n). Reading the root without removing it, peek, is O(1).
| Operation | How | Cost |
|---|---|---|
| Peek min (or max) | Read index 0 | O(1) |
| Insert | Append, sift up | O(log n) |
| Extract min (or max) | Last value to root, sift down | O(log n) |
| Heapify n values | Sift down from the last parent to the root | O(n) |
| Search, or find the max in a min heap | Scan | O(n) |
- Insert: append + sift up
- Extract: last to root + sift down, comparing both children
- Peek is O(1); search is O(n)
Terms, operations, and practical uses
The two rules
- Heap propertyEach parent is ≤ its children (min heap) or ≥ them (max heap). Equal values are allowed.
- Complete treeEvery level full except the last, which fills left to right; this is what lets the heap live in an array.
- Partial orderOnly parent-child pairs are ordered. Siblings and cousins can be in any order.
Moves
- Sift upSwap a value with its parent while it beats the parent. Used after insert.
- Sift downSwap a value with its better child while that child beats it. Used after extract and in heapify.
- HeapifySift down every parent from the last one back to the root; builds a heap in O(n).
Where heaps show up
- Priority queueServe the highest-priority item next; a heap gives O(log n) insert and extract.
- Top kA min heap of size k keeps the k largest values seen so far.
- Running medianA max heap for the lower half and a min heap for the upper half.
Code in Python, C++ and Java
def insert(heap, val):
heap.append(val)
i = len(heap) - 1
while i > 0:
parent = (i - 1) // 2
if heap[i] < heap[parent]:
heap[i], heap[parent] = heap[parent], heap[i]
i = parent
else:
break
heap = [5, 8, 12]
insert(heap, 3)
print(heap)#include <iostream>
#include <vector>
#include <algorithm>
using namespace std;
void insert(vector<int>& heap, int val) {
heap.push_back(val);
int i = heap.size() - 1;
while (i > 0) {
int parent = (i - 1) / 2;
if (heap[i] < heap[parent]) {
swap(heap[i], heap[parent]);
i = parent;
} else break;
}
}
int main() {
vector<int> heap = {5, 8, 12};
insert(heap, 3);
cout << '[';
for (size_t i = 0; i < heap.size(); i++) { if (i) cout << ", "; cout << heap[i]; }
cout << "]\n";
}import java.util.*;
public class Main {
static void insert(ArrayList<Integer> heap, int val) {
heap.add(val);
int i = heap.size() - 1;
while (i > 0) {
int parent = (i - 1) / 2;
if (heap.get(i) < heap.get(parent)) {
int temp = heap.get(i);
heap.set(i, heap.get(parent));
heap.set(parent, temp);
i = parent;
} else break;
}
}
public static void main(String[] args) {
ArrayList<Integer> heap = new ArrayList<>(Arrays.asList(5, 8, 12));
insert(heap, 3);
System.out.println(heap);
}
}Step through it
Running on [9, 5, 8, 2, 7, 3, 6] → heapify, extract-min, insert 1
Heapify in Linear Time
- Find the last parent: index ⌊n/2⌋ − 1
- Sift it down: swap with the smaller child until both children are larger
- Move one index left and repeat
- Stop after the root; the array is a heap
Heapify turns an unordered array into a heap. Inserting the n values one by one costs O(n log n). Floyd's bottom-up method does it in O(n): sift down every parent, starting at the last one, index ⌊n/2⌋ − 1, and moving back to the root. Indexes from ⌊n/2⌋ onward are leaves, and a single node is already a heap, so half the array needs no work.
Why it is linear: a sift-down costs at most the node's height, and most nodes are near the bottom. About n/2 nodes have height 0 and cost nothing, n/4 have height 1, n/8 have height 2, and so on. The sum n/4 · 1 + n/8 · 2 + n/16 · 3 + … stays below n. Repeated insertion is slower because it sifts up, and there the many leaves are the ones that may travel the full height.
Heapify is the first half of heap sort, which then extracts the root n times. It is also what Python's heapq.heapify and C++'s std::make_heap do.
- Leaves are already heaps; start at ⌊n/2⌋ − 1
- Sift-down cost ≤ height, and most nodes are low: O(n) total
- One-by-one insertion is O(n log n)
Heaps in Practice
A heap is the usual way to build a priority queue: always serve the most urgent item next. Dijkstra's and Prim's algorithms pull the closest vertex from a min heap; event simulations pull the next event by time; operating systems pick the next task by priority.
Two patterns come up often. To keep the k largest values of a long stream, hold a min heap of size k: each new value replaces the root only if it is bigger, O(log k) per value. To track a running median, keep two heaps, a max heap for the lower half and a min heap for the upper half.
Libraries mostly give a min heap: Python's heapq and Java's PriorityQueue both put the smallest first. For a max heap, store negated numbers or pass a reversed comparator. C++'s std::priority_queue is the opposite, a max heap by default. Changing a value already inside the heap needs its index, which a heap does not track; Dijkstra implementations usually push a fresh entry and skip stale ones when they come out.
- Priority queues, Dijkstra, Prim, schedulers
- Top k: min heap of size k; median: two heaps
- Python and Java: min heap; C++ priority_queue: max heap