Priority Queues
Heapsort is a fine algorithm, but the heap's most important job is a different one: being a priority queue. A priority queue holds a changing set of elements, each with a key, and always hands out the one with the highest priority next. Operating systems schedule jobs with one, simulations process events in time order with one, Dijkstra's and Prim's algorithms pick the next vertex with one, and the " smallest of a stream" problem is one. A heap supports every operation in .
The operations
A max-priority queue on a set supports:
| Operation | Effect | Heap cost |
|---|---|---|
MAXIMUM(S) |
return the element with the largest key | |
EXTRACT-MAX(S) |
remove and return it | |
INSERT(S, x, k) |
add element with key | |
INCREASE-KEY(S, x, k) |
raise 's key to , which must be at least its current key |
A min-priority queue mirrors these with MINIMUM, EXTRACT-MIN and DECREASE-KEY. Every operation uses one of the two repairs from the previous lessons: a value that may be too small for its position sinks with sift-down; a value that may be too large climbs with sift-up.
SIFT-UP(a, i) // a is a max-heap except that a[i] may exceed its parent
1 while i > 0 and a[parent(i)] < a[i]
2 swap a[i] and a[parent(i)]
3 i = parent(i)
EXTRACT-MAX(a) // a holds n >= 1 values
1 top = a[0]
2 a[0] = a[n - 1]; remove the last position
3 SIFT-DOWN(a, 0, n - 1)
4 return top
INSERT(a, k)
1 append k at position n
2 SIFT-UP(a, n)
INCREASE-KEY(a, i, k) // requires k >= a[i]
1 a[i] = k
2 SIFT-UP(a, i)Sift-up's correctness mirrors sift-down's. The invariant: the array is a heap except that may be larger than its parent, and is at least both children of . A swap moves the large value one level up and keeps both conditions; the loop stops at the root or when the parent is at least , and then nothing is violated. The path to the root has edges, so sift-up costs with one comparison per level.
A min-heap in action
The animation runs a min-priority queue: six inserts followed by two extract-min operations. Watch the second half: the last leaf moves to the root and sinks.
def push(h, x):
h.append(x)
i = len(h) - 1
while i > 0 and h[(i - 1) // 2] > h[i]: # sift up
p = (i - 1) // 2
h[p], h[i] = h[i], h[p]
i = p
def pop(h):
top = h[0]
last = h.pop()
if h:
h[0] = last
i = 0
while True: # sift down
l, r, s = 2 * i + 1, 2 * i + 2, i
if l < len(h) and h[l] < h[s]: s = l
if r < len(h) and h[r] < h[s]: s = r
if s == i: break
h[i], h[s] = h[s], h[i]
i = s
return top
h = []
for op in ["push 7", "push 4", "push 9", "push 2", "push 6", "push 1", "pop", "pop"]:
if op == "pop":
print(f"pop -> {pop(h)}: {h}")
else:
push(h, int(op.split()[1]))
print(f"{op}: {h}")push 7: [7]
push 4: [4, 7]
push 9: [4, 7, 9]
push 2: [2, 4, 9, 7]
push 6: [2, 4, 9, 7, 6]
push 1: [1, 4, 2, 7, 6, 9]
pop -> 1: [2, 4, 9, 7, 6]
pop -> 2: [4, 6, 9, 7]
The arrays match the last frame of each operation in the animation. This is exactly the practice problem Min-Heap Operations; try writing it from memory.
Increase-key and handles
INCREASE-KEY needs to know where the element sits in the array, and elements move every time a sift swaps them. Real applications therefore store, for every element, its current index (a handle), and update it on every swap. The class below keeps a dictionary pos from element names to positions; the swap helper is the only place that moves anything, so it is the only place that updates pos.
class MaxPQ:
def __init__(self):
self.a = [] # (key, name) pairs, a max-heap on key
self.pos = {} # name -> index in self.a
def _swap(self, i, j):
self.a[i], self.a[j] = self.a[j], self.a[i]
self.pos[self.a[i][1]] = i
self.pos[self.a[j][1]] = j
def _up(self, i):
while i > 0 and self.a[(i - 1) // 2][0] < self.a[i][0]:
self._swap(i, (i - 1) // 2)
i = (i - 1) // 2
def _down(self, i):
n = len(self.a)
while True:
l, r, big = 2 * i + 1, 2 * i + 2, i
if l < n and self.a[l][0] > self.a[big][0]: big = l
if r < n and self.a[r][0] > self.a[big][0]: big = r
if big == i: return
self._swap(i, big)
i = big
def insert(self, name, key):
self.a.append((key, name))
self.pos[name] = len(self.a) - 1
self._up(len(self.a) - 1)
def increase_key(self, name, key):
i = self.pos[name]
assert key >= self.a[i][0], "new key is smaller"
self.a[i] = (key, name)
self._up(i)
def extract_max(self):
self._swap(0, len(self.a) - 1)
key, name = self.a.pop()
del self.pos[name]
if self.a:
self._down(0)
return name, key
q = MaxPQ()
for name, key in [("backup", 3), ("email", 5), ("render", 8), ("index", 2), ("upload", 6)]:
q.insert(name, key)
print("heap:", q.a)
q.increase_key("index", 9) # an urgent job jumps the queue
print("after increase-key:", q.a)
print("positions consistent:", all(q.a[i][1] == name for name, i in q.pos.items()))
while q.a:
print("extract-max ->", q.extract_max())heap: [(8, 'render'), (6, 'upload'), (5, 'email'), (2, 'index'), (3, 'backup')]
after increase-key: [(9, 'index'), (8, 'render'), (5, 'email'), (6, 'upload'), (3, 'backup')]
positions consistent: True
extract-max -> ('index', 9)
extract-max -> ('render', 8)
extract-max -> ('upload', 6)
extract-max -> ('email', 5)
extract-max -> ('backup', 3)
In C++
The standard library's std::priority_queue is a max-heap without increase-key. The version below implements insert, extract_max and increase_key on a std::vector, with a position array for handles (elements are numbered to ), and runs the same jobs.
#include <cstdio>
#include <string>
#include <utility>
#include <vector>
struct MaxPQ {
std::vector<int> heap; // element ids, a max-heap on key[id]
std::vector<int> key, pos;
explicit MaxPQ(int m) : key(m), pos(m, -1) {}
bool less(int i, int j) const { return key[heap[i]] < key[heap[j]]; }
void swap_at(int i, int j) {
std::swap(heap[i], heap[j]);
pos[heap[i]] = i;
pos[heap[j]] = j;
}
void up(int i) {
while (i > 0 && less((i - 1) / 2, i)) { swap_at(i, (i - 1) / 2); i = (i - 1) / 2; }
}
void down(int i) {
int n = static_cast<int>(heap.size());
for (;;) {
int l = 2 * i + 1, r = l + 1, big = i;
if (l < n && less(big, l)) big = l;
if (r < n && less(big, r)) big = r;
if (big == i) return;
swap_at(i, big);
i = big;
}
}
void insert(int id, int k) {
key[id] = k;
heap.push_back(id);
pos[id] = static_cast<int>(heap.size()) - 1;
up(pos[id]);
}
void increase_key(int id, int k) { key[id] = k; up(pos[id]); }
int extract_max() {
int top = heap[0];
swap_at(0, static_cast<int>(heap.size()) - 1);
heap.pop_back();
pos[top] = -1;
if (!heap.empty()) down(0);
return top;
}
};
int main() {
std::vector<std::string> names = {"backup", "email", "render", "index", "upload"};
std::vector<int> keys = {3, 5, 8, 2, 6};
MaxPQ q(static_cast<int>(names.size()));
for (int id = 0; id < 5; ++id) q.insert(id, keys[id]);
q.increase_key(3, 9);
while (!q.heap.empty()) {
int id = q.extract_max();
std::printf("extract-max -> %s %d\n", names[id].c_str(), q.key[id]);
}
}extract-max -> index 9
extract-max -> render 8
extract-max -> upload 6
extract-max -> email 5
extract-max -> backup 3
Applications in one line each
- Heapsort is inserts (or one build) followed by extract-max operations.
- Merging sorted lists of total length : keep the current head of each list in a min-heap of size , and repeatedly extract the smallest and insert its successor. Each of the outputs costs , so the merge costs .
- The largest of a stream: keep a min-heap of the best seen so far; a new value replaces the root if it is larger. time and memory. See the practice problem K-th Largest.
- Event simulation and shortest paths: the next event or the nearest unvisited vertex is an extract-min; a shorter path found to a vertex is a decrease-key.
The -way merge with Python's heapq, counting comparisons to confirm the behaviour:
import heapq, math, random
class Key:
count = 0
def __init__(self, v, src):
self.v, self.src = v, src
def __lt__(self, other):
Key.count += 1
return self.v < other.v
def k_way_merge(lists):
heap = [Key(lst[0], (i, 0)) for i, lst in enumerate(lists) if lst]
heapq.heapify(heap)
out = []
while heap:
top = heap[0]
out.append(top.v)
i, j = top.src
if j + 1 < len(lists[i]):
heapq.heapreplace(heap, Key(lists[i][j + 1], (i, j + 1))) # pop + push in one sift
else:
heapq.heappop(heap)
return out
rng = random.Random(11)
n = 4096
for k in [2, 8, 64]:
values = [rng.random() for _ in range(n)]
lists = [sorted(values[i::k]) for i in range(k)]
Key.count = 0
merged = k_way_merge(lists)
assert merged == sorted(values)
print(f"k = {k:>2}: {Key.count:>6} comparisons, n lg k = {n * math.log2(k):>6.0f}")k = 2: 4094 comparisons, n lg k = 4096
k = 8: 14925 comparisons, n lg k = 12288
k = 64: 28147 comparisons, n lg k = 24576
The counts grow with as predicted, and stay within about 20 percent of . That is because heapq repairs the root the bottom-up way mentioned in Heapsort: it moves the hole down to a leaf with one comparison per level (which child is smaller?) and then lets the new value climb back up, which is usually only a step or two.
Test yourself
In EXTRACT-MAX, why is the **last** element moved to the root before sifting down?
- Because it is the smallest element
- Because removing the last position keeps the nearly complete shape, and then only one value is out of place
- Because it makes the operation stable
- Because sift-up cannot be used
Which repair does INCREASE-KEY on a max-heap need?
- Sift-down from the changed position
- Sift-up from the changed position
- Rebuilding the whole heap
- None, the heap property cannot break
How long does merging sorted lists with elements in total take with a min-heap of the list heads?
Why does a priority queue with INCREASE-KEY need handles (stored positions)?
- To keep the heap balanced
- Because finding an element by value in a heap would take time, and elements move with every swap
- Because Python lists cannot be indexed
- To make extract-max faster