Sub topic 8
Kruskal's Algorithm: Growing a Forest from Sorted Edges
This chapter assumes you know the cut property, the generic greedy MST strategy, and the DisjointSet class from the previous chapter. You should also be comfortable with Python's sorted and with Big-O notation.
The Idea
Kruskal's algorithm treats every vertex as its own tiny tree. It then looks at edges from lightest to heaviest. Each edge either joins two different trees or connects two vertices that are already in the same tree:
- If the edge joins two different trees, keep it. The two trees merge into one.
- If both endpoints are already in the same tree, skip the edge. Adding it would create a cycle.
At every step the kept edges form a forest, which is a set of trees with no cycles. When the forest has V − 1 edges, it is a single spanning tree.
Why it is correct
Suppose the current edge (u, v) joins tree A to some other tree. Take the cut that puts tree A on one side and every other vertex on the other side. No kept edge crosses this cut. Every lighter edge that crosses it was already looked at, and each of those would have been kept, so none exists. That makes (u, v) the lightest edge crossing the cut, and the cut property says it is safe to add.
Implementation
The disjoint-set structure answers the question "are u and v already in the same tree?" in near-constant time. Its union method returns False when they are, and that return value is the cycle check.
class DisjointSet:
def __init__(self, n):
self.parent = list(range(n))
self.rank = [0] * n
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
if self.rank[ra] < self.rank[rb]:
ra, rb = rb, ra
self.parent[rb] = ra
if self.rank[ra] == self.rank[rb]:
self.rank[ra] += 1
return True
def kruskal(n, edges):
# edges: list of (weight, u, v) tuples with vertices numbered 0..n-1
ds = DisjointSet(n)
mst = []
total = 0
for w, u, v in sorted(edges):
if ds.union(u, v):
mst.append((u, v, w))
total += w
if len(mst) == n - 1:
break
return total, mst
edges = [(1, 0, 1), (4, 0, 2), (3, 1, 2), (2, 1, 3), (5, 2, 3)]
print(kruskal(4, edges)) # (6, [(0, 1, 1), (1, 3, 2), (1, 2, 3)])Tracing It by Hand
Sorted by weight, the edges are 0–1 (1), 1–3 (2), 1–2 (3), 0–2 (4), and 2–3 (5).
| Step | Edge | Weight | Same tree? | Action | Components after |
|---|---|---|---|---|---|
| 1 | 0–1 | 1 | No | Keep | {0,1} {2} {3} |
| 2 | 1–3 | 2 | No | Keep | {0,1,3} {2} |
| 3 | 1–2 | 3 | No | Keep | {0,1,2,3} |
| — | 0–2, 2–3 | 4, 5 | — | Never examined | Loop stopped at V − 1 edges |
The total weight is 1 + 2 + 3 = 6. If the loop had not stopped early, both remaining edges would have been rejected, because their endpoints are already in the same tree.
Running Time
Sorting takes O(E log E) time. Since E ≤ V², log E ≤ 2 log V, so this equals O(E log V). The loop makes at most E union calls. With union by rank and path compression, each call costs O(α(V)) amortized, where α is the inverse Ackermann function and is at most 4 for any realistic input. Sorting dominates the total cost.
Common Errors
- Adding both directions of an edge. An undirected edge only needs to appear once. A duplicate copy is harmless because
unionrejects it, but it adds sorting work for nothing. - Assuming V − 1 edges come out. On a disconnected graph the loop never reaches
n - 1and returns a minimum spanning forest. Checklen(mst)if you need a single tree. - Writing your own cycle check with DFS. Searching the forest for a path before each edge costs O(V) per edge, which makes the algorithm O(EV). Use the disjoint-set structure.
Exercise
Run Kruskal's algorithm on vertices 0–3 with edges 0–1 (2), 1–2 (2), 0–2 (1), 2–3 (4), 1–3 (3). Which edges does it keep, which does it reject, and what is the total weight?
Show answer
Sorted order is 0–2 (1), 0–1 (2), 1–2 (2), 1–3 (3), 2–3 (4). It keeps 0–2 and 0–1. It rejects 1–2 because 1 and 2 are already connected through 0. It keeps 1–3, which brings the edge count to V − 1 = 3, so the loop stops before reaching 2–3. The total weight is 1 + 2 + 3 = 6.
Exercise
Why does Kruskal's running time stay O(E log V) even if you replace path halving with no path compression but keep union by rank?
Show answer
Union by rank alone keeps tree height at O(log V), so each find costs O(log V). The E union calls then cost O(E log V), which matches the sorting cost and leaves the total at O(E log V).