Sub topic 20
Kruskal's and Prim's algorithms
This chapter assumes you know the cut property from the previous chapter, union-find with union by rank and path compression, and binary heaps. Both algorithms build a minimum spanning tree (MST) of a connected, weighted, undirected graph. Both are greedy, and the cut property justifies both.
Two ways to grow the same tree
Kruskal's algorithm is edge-centric. It sorts all edges by weight and adds each edge unless it would close a cycle. At any moment the chosen edges form a forest that merges into one tree.
Prim's algorithm is vertex-centric. It starts from one vertex and repeatedly adds the cheapest edge that connects the current tree to a vertex outside it. At any moment the chosen edges form a single tree.
Each addition is safe because of the cut property. In Kruskal's case, the edge being added is the lightest edge leaving one component, so it is the lightest edge crossing the cut between that component and the rest. In Prim's case, the cut is between the tree and the remaining vertices.
Kruskal's algorithm
The cycle test is find(u) != find(v). With union by rank and path compression, each find or union costs nearly constant amortized time. The sort dominates, so the total is O(E log E), which equals O(E log V) because E < V².
def kruskal(n, edges):
parent = list(range(n))
rank = [0] * n
def find(x):
while parent[x] != x:
parent[x] = parent[parent[x]]
x = parent[x]
return x
def union(a, b):
ra, rb = find(a), find(b)
if ra == rb:
return False
if rank[ra] < rank[rb]:
ra, rb = rb, ra
parent[rb] = ra
if rank[ra] == rank[rb]:
rank[ra] += 1
return True
total = 0
for w, u, v in sorted(edges):
if union(u, v):
total += w
return total
print(kruskal(4, [(1, 0, 1), (4, 0, 2), (3, 1, 2), (2, 1, 3), (5, 2, 3)])) # 6Trace on this graph. The sorted edges are weights 1 (0-1), 2 (1-3), 3 (1-2), 4 (0-2) and 5 (2-3). The algorithm takes 1, 2 and 3. Edge 4 would join vertices 0 and 2, which are already connected, so it is skipped. The total is 6.
Prim's algorithm
Prim's algorithm keeps a priority queue of candidate edges as (weight, vertex) pairs. It pops the cheapest one. If the vertex is already in the tree, it discards the entry (lazy deletion). Otherwise it adds the vertex and pushes that vertex's edges to unvisited neighbours.
import heapq
def prim(graph, start):
visited = set()
heap = [(0, start)]
total = 0
while heap:
w, u = heapq.heappop(heap)
if u in visited:
continue
visited.add(u)
total += w
for v, wt in graph[u]:
if v not in visited:
heapq.heappush(heap, (wt, v))
return total
g = {
0: [(1, 1), (2, 4)],
1: [(0, 1), (2, 3), (3, 2)],
2: [(0, 4), (1, 3), (3, 5)],
3: [(1, 2), (2, 5)],
}
print(prim(g, 0)) # 6Here each adjacency entry is (neighbour, weight). Prim's algorithm adds vertices in the order 0, 1, 3, 2, using edges of weight 1, 2 and 3.
Complexity comparison
| Algorithm and structure | Time | Best fit |
|---|---|---|
| Kruskal, sort plus union-find | O(E log E) = O(E log V) | Sparse graphs, or edges already sorted |
| Prim, binary heap and adjacency list | O((V + E) log V) = O(E log V) | General graphs |
| Prim, array and adjacency matrix | O(V²) | Dense graphs |
| Prim, Fibonacci heap | O(E + V log V) | Theoretical interest |
For a dense graph with E near V², O(V²) beats O(E log V). For a sparse graph with E near V, both heap-based versions are O(V log V).
Edge cases and common errors
- Ties in weights. Different tie-breaking can produce different MSTs, but all have the same total weight. If all edge weights are distinct, the MST is unique.
- Cycle property. If an edge is the strictly heaviest edge on some cycle, no MST contains it.
- Disconnected graphs. Kruskal's algorithm yields a minimum spanning forest. The Prim code above covers only the start vertex's component. Rerun it from each unvisited vertex to get a forest.
- Negative weights. Both algorithms work unchanged, because only the order of weights matters. This differs from Dijkstra's algorithm.
- Maximum spanning tree. Sort in descending order, or negate the weights.
- Confusing Prim with Dijkstra. Prim's algorithm keys each vertex by the weight of a single connecting edge. Dijkstra's algorithm keys each vertex by the total distance from the source.
- Forgetting the stopping rule. A spanning tree has exactly V − 1 edges. Kruskal's algorithm can stop early once it has that many.
Exercises
Exercise
A graph has vertices A to E and edges A-B 2, A-C 3, B-C 1, B-D 4, C-D 5, C-E 6, D-E 7. Find the MST weight using Kruskal's algorithm, and give the order in which Prim's algorithm starting at A adds vertices.
Show answer
Kruskal sorts the edges and takes B-C (1), A-B (2) and skips A-C (3), which would form a cycle. It then takes B-D (4), skips C-D (5), takes C-E (6) and skips D-E (7). The weight is 1 + 2 + 4 + 6 = 13. Prim from A adds B (edge 2), then C (edge 1), then D (edge 4), then E (edge 6), for the same total of 13.
Exercise
Why does the Prim code above still give a correct MST total when a vertex is pushed onto the heap several times?
Show answer
A vertex may be pushed once per edge that reaches it from the tree. The cheapest entry is popped first and the vertex is marked visited. Later, more expensive entries for the same vertex are discarded by the if u in visited check. The heap can hold up to E entries, so each push or pop costs O(log E) = O(log V), which gives O(E log V) overall.