Prim's Algorithm with a Binary Heap
Kruskal's algorithm grows a forest that eventually merges into one tree. Prim's algorithm (Jarník 1930, Prim 1957, Dijkstra 1959) grows a single tree from a root vertex, and at every step adds the cheapest edge that leaves the tree. That edge is a light edge for the cut between the tree and the rest of the graph, which respects the tree, so it is safe by the cut property. The interesting part is the bookkeeping: for every vertex outside the tree, Prim keeps the weight of the cheapest edge connecting it to the tree, in a min-priority queue, and lowers it with decrease-key whenever the tree grows. The DSA course shows the idea by example.
The algorithm
Every vertex has a key, the weight of the lightest edge known from the tree to ( if none), and a parent , the tree end of that edge.
PRIM(G, w, r)
1 for each vertex u in G.V
2 u.key = infinity; u.pi = NIL
3 r.key = 0
4 Q = a min-priority queue of all vertices, keyed by key
5 while Q is not empty
6 u = EXTRACT-MIN(Q) // add u and edge (u.pi, u) to the tree
7 for each v in G.Adj[u]
8 if v is in Q and w(u, v) < v.key
9 v.pi = u
10 DECREASE-KEY(Q, v, w(u, v))
11 return the edges (v.pi, v) for v != rCorrectness. Invariant: before each EXTRACT-MIN, the edges form a tree on the vertices not in , is contained in some MST, and for each with , is the weight of the lightest edge from to the tree. The extracted has the smallest key, so is a light edge crossing the cut (tree, ), and the cut respects : the edge is safe. Lines 7 to 10 restore the key invariant, since the only new edges into the tree are those at .
Watching it work
The graph is the one from the Kruskal lesson. Each label is the vertex's current key; a check mark means the vertex is in the tree.
The Python version keeps an indexed binary min-heap, the priority queue with handles from Sorting & Order Statistics turned into a min-heap: a dictionary pos records where each vertex sits in the heap array, so DECREASE-KEY can find it and sift it up in . Ties in the key are broken by name, as in the animation.
class MinHeap:
def __init__(self, keys):
self.a = sorted((k, v) for v, k in keys.items()) # a sorted array is a valid heap
self.pos = {v: i for i, (k, v) in enumerate(self.a)}
self.sifts = 0
def _swap(self, i, j):
self.a[i], self.a[j] = self.a[j], self.a[i]
self.pos[self.a[i][1]], self.pos[self.a[j][1]] = i, j
self.sifts += 1
def _up(self, i):
while i > 0 and self.a[i] < self.a[(i - 1) // 2]:
self._swap(i, (i - 1) // 2)
i = (i - 1) // 2
def _down(self, i):
while True:
small, l, r = i, 2 * i + 1, 2 * i + 2
if l < len(self.a) and self.a[l] < self.a[small]: small = l
if r < len(self.a) and self.a[r] < self.a[small]: small = r
if small == i: return
self._swap(i, small)
i = small
def extract_min(self):
self._swap(0, len(self.a) - 1)
k, v = self.a.pop()
del self.pos[v]
self._down(0)
return v
def decrease_key(self, v, k):
i = self.pos[v]
self.a[i] = (k, v)
self._up(i)
def __contains__(self, v):
return v in self.pos
edges = [("A", "B", 4), ("A", "C", 3), ("B", "C", 2), ("B", "D", 5), ("C", "E", 7), ("D", "E", 6),
("D", "F", 9), ("E", "G", 8), ("F", "G", 10), ("F", "H", 1), ("G", "H", 11), ("E", "F", 12)]
adj = {v: [] for v in "ABCDEFGH"}
for u, v, w in edges:
adj[u].append((v, w)); adj[v].append((u, w))
for v in adj:
adj[v].sort()
INF = float("inf")
key = {v: INF for v in adj}
parent = {v: None for v in adj}
key["A"] = 0
q = MinHeap(key)
total = 0
while q.a:
u = q.extract_min()
total += key[u]
print(f"add {u}" + (f" via {parent[u]}-{u} ({key[u]}), tree weight {total}" if parent[u] else ""))
for v, w in adj[u]:
if v in q and w < key[v]:
old, key[v], parent[v] = key[v], w, u
q.decrease_key(v, w)
print(f" key[{v}]: {old} -> {w} (edge {u}-{v})")
print("MST weight", total, "with", q.sifts, "heap swaps")add A
key[B]: inf -> 4 (edge A-B)
key[C]: inf -> 3 (edge A-C)
add C via A-C (3), tree weight 3
key[B]: 4 -> 2 (edge C-B)
key[E]: inf -> 7 (edge C-E)
add B via C-B (2), tree weight 5
key[D]: inf -> 5 (edge B-D)
add D via B-D (5), tree weight 10
key[E]: 7 -> 6 (edge D-E)
key[F]: inf -> 9 (edge D-F)
add E via D-E (6), tree weight 16
key[G]: inf -> 8 (edge E-G)
add G via E-G (8), tree weight 24
key[H]: inf -> 11 (edge G-H)
add F via D-F (9), tree weight 33
key[H]: 11 -> 1 (edge F-H)
add H via F-H (1), tree weight 34
MST weight 34 with 21 heap swaps
Prim adds the vertices in the order and builds the same tree as Kruskal, of weight 34; the graph's weights are distinct, so the MST is unique (next lesson). Note the update of : its key drops from 4 (edge -) to 2 when joins, because - is cheaper.
Running time and the decrease-key detail
With a binary heap: building the heap is , there are EXTRACT-MIN operations at each, and DECREASE-KEY runs at most once per adjacency-list entry, times at each. The test " is in " is with the pos map. The total is , the same as Kruskal.
Without decrease-key. Python's heapq and C++'s std::priority_queue cannot find an element inside the heap, so they have no DECREASE-KEY. The standard workaround is lazy deletion: instead of lowering 's key, push a new pair , and when a pair whose vertex is already in the tree is popped, discard it. The heap can then hold up to entries, so each operation costs and the bound is still , with more memory.
With an array. For a dense graph, keep the keys in a plain array and find the minimum by scanning it: per extraction and per key update, in total, which beats when is close to . With a Fibonacci heap, whose DECREASE-KEY is amortized, Prim runs in .
The program counts the elementary steps of the three versions on a sparse and a dense random graph: heap swaps and pushes for the heaps, array cells scanned for the array version.
import heapq, random
def random_graph(n, m, rng):
adj = [[] for _ in range(n)]
pairs = {(i, i + 1) for i in range(n - 1)} # keep it connected
while len(pairs) < m:
u, v = sorted(rng.sample(range(n), 2))
pairs.add((u, v))
for u, v in pairs:
w = rng.randint(1, 10 ** 6)
adj[u].append((v, w)); adj[v].append((u, w))
return adj
def prim_lazy(adj):
n, in_tree, total, work = len(adj), [False] * len(adj), 0, 0
pq = [(0, 0)]
while pq:
w, u = heapq.heappop(pq)
work += 1
if in_tree[u]:
continue # stale entry
in_tree[u] = True
total += w
for v, wv in adj[u]:
if not in_tree[v]:
heapq.heappush(pq, (wv, v))
work += 1
return total, work
def prim_array(adj):
n, INF = len(adj), float("inf")
key, in_tree, total, work = [INF] * n, [False] * n, 0, 0
key[0] = 0
for _ in range(n):
u = min((v for v in range(n) if not in_tree[v]), key=key.__getitem__)
work += n # one scan of the key array
in_tree[u] = True
total += key[u]
for v, w in adj[u]:
if not in_tree[v] and w < key[v]:
key[v] = w
return total, work
rng = random.Random(6)
for name, n, m in [("sparse", 2000, 8000), ("dense", 300, 40000)]:
adj = random_graph(n, m, rng)
t1, w1 = prim_lazy(adj)
t2, w2 = prim_array(adj)
assert t1 == t2
print(f"{name:6}: V = {n}, E = {m}; lazy heap {w1:,} pushes+pops, array {w2:,} cells scanned")sparse: V = 2000, E = 8000; lazy heap 16,001 pushes+pops, array 4,000,000 cells scanned
dense : V = 300, E = 40000; lazy heap 80,001 pushes+pops, array 90,000 cells scanned
On the sparse graph the heap version does about sixteen thousand operations against four million array cells; on the dense graph the array version scans about as many cells as the heap version makes pushes and pops, and each heap operation costs a logarithmic number of comparisons on top.
In C++
The C++ version uses std::priority_queue with lazy deletion, the usual way to write Prim (and Dijkstra) with the standard library.
#include <cstdio>
#include <functional>
#include <queue>
#include <utility>
#include <vector>
int main() {
const int n = 8; // A..H
struct E { char u, v; int w; };
std::vector<E> edges = {{'A','B',4}, {'A','C',3}, {'B','C',2}, {'B','D',5}, {'C','E',7}, {'D','E',6},
{'D','F',9}, {'E','G',8}, {'F','G',10}, {'F','H',1}, {'G','H',11}, {'E','F',12}};
std::vector<std::vector<std::pair<int, int>>> adj(n); // (neighbour, weight)
for (auto e : edges) {
adj[e.u - 'A'].push_back({e.v - 'A', e.w});
adj[e.v - 'A'].push_back({e.u - 'A', e.w});
}
using Item = std::pair<int, std::pair<int, int>>; // (weight, (vertex, parent))
std::priority_queue<Item, std::vector<Item>, std::greater<Item>> pq;
std::vector<bool> in_tree(n, false);
pq.push({0, {0, -1}});
int total = 0, stale = 0;
while (!pq.empty()) {
auto [w, up] = pq.top();
pq.pop();
auto [u, p] = up;
if (in_tree[u]) { ++stale; continue; }
in_tree[u] = true;
total += w;
if (p >= 0) std::printf("add %c via %c-%c (%d)\n", 'A' + u, 'A' + p, 'A' + u, w);
for (auto [v, wv] : adj[u])
if (!in_tree[v]) pq.push({wv, {v, u}});
}
std::printf("MST weight %d, %d stale entries discarded\n", total, stale);
}add C via A-C (3)
add B via C-B (2)
add D via B-D (5)
add E via D-E (6)
add G via E-G (8)
add F via D-F (9)
add H via F-H (1)
MST weight 34, 5 stale entries discarded
Test yourself
Prim's algorithm adds vertex to the tree. Which keys can change?
- All keys
- Only the keys of 's neighbours that are still outside the tree
- Only 's key
- None until the next extraction
What is the running time of Prim's algorithm with a binary heap and adjacency lists?
With heapq (no decrease-key), how does Prim handle a vertex whose key drops?
- It rebuilds the heap
- It pushes a new (key, vertex) entry and discards outdated entries when they are popped
- It ignores the new key
- It cannot be implemented
For which graphs is the array version of Prim the best choice?
- Sparse graphs,
- Dense graphs, close to
- Trees
- Graphs with negative weights