Kruskal's Algorithm
Kruskal's algorithm finds a minimum spanning tree in a completely different way from Prim's. Instead of growing one tree, it looks at all edges sorted from cheapest to most expensive and adds each edge unless it would create a cycle. At first the chosen edges form many little trees (a forest); they gradually merge until one tree spans everything.
The algorithm
- Sort all edges by weight.
- Start with every vertex in its own group.
- For each edge
u-vin sorted order: ifuandvare in different groups, add the edge and merge the two groups. If they are in the same group, the edge would close a cycle, so skip it. - Stop after
V - 1edges.
The question "are u and v already connected?" is answered efficiently by a union-find (disjoint set) structure.
Union-find
Each group is a little tree of parent pointers; the root represents the group. find(x) follows parents to the root; union(a, b) attaches one root under the other. Two tricks keep the trees flat, making both operations almost O(1):
- Path compression: during
find, point visited nodes closer to the root. - Union by size: attach the smaller tree under the larger one.
class UnionFind:
def __init__(self, items):
self.parent = {x: x for x in items}
self.size = {x: 1 for x in items}
def find(self, x):
while self.parent[x] != x:
self.parent[x] = self.parent[self.parent[x]] # path compression (halving)
x = self.parent[x]
return x
def union(self, a, b):
ra, rb = self.find(a), self.find(b)
if ra == rb:
return False # already in the same group
if self.size[ra] < self.size[rb]:
ra, rb = rb, ra
self.parent[rb] = ra # smaller tree under the larger
self.size[ra] += self.size[rb]
return True
uf = UnionFind("ABCDE")
print(uf.union("A", "B"), uf.union("C", "D"), uf.union("B", "D"))
print(uf.union("A", "C")) # already connected
print(uf.find("D") == uf.find("A"), uf.find("E") == uf.find("A"))True True True
False
True False
Kruskal's algorithm on the example graph
The same graph as in the previous two lessons:
class UnionFind:
def __init__(self, items):
self.parent = {x: x for x in items}
def find(self, x):
while self.parent[x] != x:
self.parent[x] = self.parent[self.parent[x]]
x = self.parent[x]
return x
def union(self, a, b):
ra, rb = self.find(a), self.find(b)
if ra == rb:
return False
self.parent[rb] = ra
return True
edges = [("A", "B", 7), ("A", "C", 3), ("B", "C", 2), ("B", "D", 5), ("C", "D", 6),
("C", "E", 4), ("D", "E", 8), ("D", "F", 1), ("E", "F", 9)]
vertices = "ABCDEF"
def kruskal(vertices, edges):
uf = UnionFind(vertices)
mst = []
for u, v, w in sorted(edges, key=lambda e: e[2]):
if uf.union(u, v):
mst.append((u, v, w))
print(f"take {u}-{v} ({w})")
if len(mst) == len(vertices) - 1:
break
else:
print(f"skip {u}-{v} ({w}): would close a cycle")
return mst
mst = kruskal(vertices, edges)
print("total:", sum(w for *_, w in mst))take D-F (1)
take B-C (2)
take A-C (3)
take C-E (4)
take B-D (5)
total: 15
The five cheapest edges happen to form no cycle, so they are all taken and the algorithm stops: the remaining edges (C-D, A-B, D-E, E-F) are never even looked at. Same tree, same total (15) as Prim's algorithm.
Seeing the skipped edges
On a graph with more short cycles, many cheap edges must be skipped. Here are four towns where every pair is connected:
edges = [("P", "Q", 1), ("Q", "R", 2), ("P", "R", 3), ("R", "S", 4), ("P", "S", 5), ("Q", "S", 6)]
group = {v: v for v in "PQRS"}
def find(x):
while group[x] != x:
x = group[x]
return x
total = 0
for u, v, w in sorted(edges, key=lambda e: e[2]):
ru, rv = find(u), find(v)
if ru == rv:
print(f"skip {u}-{v} ({w})")
continue
group[ru] = rv
total += w
groups = {}
for x in "PQRS":
groups.setdefault(find(x), []).append(x)
print(f"take {u}-{v} ({w}) groups: {sorted(groups.values())}")
print("total:", total)take P-Q (1) groups: [['P', 'Q'], ['R'], ['S']]
take Q-R (2) groups: [['P', 'Q', 'R'], ['S']]
skip P-R (3)
take R-S (4) groups: [['P', 'Q', 'R', 'S']]
skip P-S (5)
skip Q-S (6)
total: 7
Watch the groups merge: four singletons become one group after three edges. P-R is skipped because P and R are already connected through Q. This version has no early stop, so it also checks (and skips) the last two edges after the tree is complete.
Clustering with Kruskal
Stopping Kruskal's algorithm early leaves several groups: the cheapest way to split the vertices into k clusters of "close" items. Here are points on a line (the weight is the gap between them), split into 3 clusters by stopping after n - 3 merges:
points = [1, 2, 4, 11, 12, 14, 30, 31]
edges = sorted((abs(a - b), a, b) for i, a in enumerate(points) for b in points[i + 1:])
group = {p: p for p in points}
def find(x):
while group[x] != x:
x = group[x]
return x
merges = 0
for w, a, b in edges:
if merges == len(points) - 3:
break
ra, rb = find(a), find(b)
if ra != rb:
group[ra] = rb
merges += 1
clusters = {}
for p in points:
clusters.setdefault(find(p), []).append(p)
print(sorted(clusters.values()))[[1, 2, 4], [11, 12, 14], [30, 31]]
Prim vs Kruskal
| Prim's | Kruskal's | |
|---|---|---|
| Grows | one tree | a forest that merges |
| Main data structure | priority queue | sorted edge list + union-find |
| Time | O(E log V) |
O(E log E) (the sort dominates) |
| Graph format | adjacency list | edge list |
| Disconnected graph | spans only the start's component | gives a minimum spanning forest |
| Often preferred for | dense graphs | sparse graphs, or edges already sorted |
Test yourself
In which order does Kruskal's algorithm consider edges?
- Breadth-first from a start vertex
- From cheapest to most expensive
- From most expensive to cheapest
- In input order
When does Kruskal's algorithm skip an edge?
- When its weight is above the average
- When both endpoints are already in the same group (it would form a cycle)
- When it touches the start vertex
- Never
What does union-find's find(x) return?
- The number of elements
- The representative (root) of x's group
- x's neighbours
- The edge weight