Sub topic 8
Kruskal's Algorithm: Growing a Forest from Sorted Edges
This chapter assumes you have read the earlier chapters on the cut property, the generic greedy MST strategy, and the disjoint-set (union-find) structure. It also assumes you can read Python classes, know what sorting costs in Big-O terms, and can work with edge lists. The disjoint-set code is repeated here so the examples run as shown. Its internals are not explained again.
The Idea in One Paragraph
Kruskal's algorithm looks at every edge of the graph from lightest to heaviest. For each edge it asks one question: do the two endpoints already belong to the same piece of the partial solution? If they do not, the edge joins two separate pieces, so the algorithm keeps it. If they do, the edge would close a cycle, so the algorithm throws it away. The kept edges start out as a forest of single-vertex trees. These trees merge step by step until only one tree is left.
A forest is a graph with no cycles. It may have several connected pieces, and each piece is a tree. Kruskal's partial solution is always a forest. Prim's algorithm, covered later, works differently: its partial solution is always one tree.
Why Kruskal's Choices Are Safe
The generic greedy strategy says you may add any edge that is the lightest edge crossing some cut that the current edge set respects. Kruskal's algorithm fits this rule.
Say the algorithm is about to accept edge (u, v) with weight w, and u and v sit in different components. Let C be the component that contains u. Cut the graph into C on one side and every other vertex on the other side. No accepted edge crosses this cut, because C is a whole component. Every edge lighter than w was examined earlier. Each of those edges was either accepted, so it lies inside some component, or rejected, so both its endpoints were already in the same component. Either way, no lighter edge crosses the cut. That makes (u, v) a lightest crossing edge, and the cut property says it is safe to add.
Rejected edges are safe to discard because of the cycle property. When the algorithm reaches a rejected edge, its endpoints are already joined by a path of edges that are no heavier than it. That edge is the heaviest edge on the cycle it would close, so leaving it out never makes the tree worse.
The Algorithm Step by Step
- Put each vertex in its own set. These sets are the components of the forest.
- Sort all edges by weight, lightest first.
- For each edge (u, v) in sorted order, find the set of u and the set of v.
- If the sets differ, add the edge to the result and merge the two sets.
- If the sets are the same, skip the edge.
- Stop when you have accepted V − 1 edges, or when you run out of edges.
Implementation
Kruskal's algorithm uses the disjoint set for one check: union returns False when the endpoints already share a root. That single return value works as the cycle test and the merge together.
class DisjointSet:
def __init__(self, n):
self.parent = list(range(n))
self.rank = [0] * n
def find(self, x):
# Path halving: point each visited node at its grandparent.
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 # already in the same set; edge would form a cycle
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)])The edge tuples put the weight first on purpose. Python compares tuples element by element, so sorted(edges) orders by weight. When weights tie, it falls back to comparing u and then v. The early break is an optimization. Once a connected graph has V − 1 accepted edges, it is spanning, and every later edge would be rejected anyway.
Tracing a Larger Example by Hand
The four-vertex example above accepts its first three edges and stops, so it never shows a rejection. The six-vertex graph below does.
edges6 = [(1, 0, 1), (2, 2, 3), (3, 0, 2), (3, 1, 2), (4, 3, 4),
(5, 1, 3), (6, 4, 5), (7, 3, 5), (8, 2, 5)]
print(kruskal(6, edges6))
# (16, [(0, 1, 1), (2, 3, 2), (0, 2, 3), (3, 4, 4), (4, 5, 6)])| Step | Edge (w, u, v) | Same set? | Action | Components after |
|---|---|---|---|---|
| 1 | (1, 0, 1) | no | accept | {0,1} {2} {3} {4} {5} |
| 2 | (2, 2, 3) | no | accept | {0,1} {2,3} {4} {5} |
| 3 | (3, 0, 2) | no | accept | {0,1,2,3} {4} {5} |
| 4 | (3, 1, 2) | yes | reject | unchanged |
| 5 | (4, 3, 4) | no | accept | {0,1,2,3,4} {5} |
| 6 | (5, 1, 3) | yes | reject | unchanged |
| 7 | (6, 4, 5) | no | accept, 5 edges, stop | {0,1,2,3,4,5} |
The total is 1 + 2 + 3 + 4 + 6 = 16. The edges (7, 3, 5) and (8, 2, 5) are never examined. Step 4 breaks a tie: edges 0–2 and 1–2 both weigh 3. Whichever one comes first is accepted and the other is rejected. Either choice gives a valid MST with the same total weight.
Running Time
| Phase | Cost |
|---|---|
| Build the disjoint set | O(V) |
| Sort the edges | O(E log E) |
| Up to 2E finds and V − 1 unions | O(E α(V)) |
| Total | O(E log E) = O(E log V) |
Here α is the inverse Ackermann function. It is at most 4 for any input size you will ever see. Sorting dominates the cost. Because a simple graph has E ≤ V², log E ≤ 2 log V, so O(E log E) and O(E log V) are the same bound.
Sorting is the real bottleneck. If the edges arrive already sorted, or the weights are small integers that counting sort or radix sort can handle, Kruskal's algorithm runs in close to linear time, O(E α(V)). The early exit does not improve the worst case, because the heaviest edge might belong to the MST. It does help a lot in practice on graphs with many heavy edges.
Edge Cases and Common Errors
The "visited vertex" mistake
A common wrong version keeps a set of vertices that already touch an accepted edge, and rejects an edge when both endpoints are in that set. This rule rejects edges that join two different components. In the trace above, by step 3 vertices 0, 1, 2, and 3 have all been touched, so the wrong version rejects edge (3, 0, 2) and never connects {0,1} to {2,3}. The right question is whether the endpoints share a component, which only the disjoint set answers correctly.
Sorting keys and tie-breaking
Ties never change the total weight of the MST. They can change which edges end up in it.
Input quirks
- Self-loops such as (w, 3, 3) are always rejected, because
find(3) == find(3). You do not need special handling. - Parallel edges between the same pair of vertices are handled automatically. The lightest copy comes first and wins, and the later copies are rejected.
- Negative and zero weights are fine. The algorithm only compares weights and never adds them up during its decisions.
- Vertices must be numbered 0 to n − 1. If your labels are strings, map them to indices first. The disjoint set uses vertices as list indices.
- Kruskal's algorithm applies only to undirected graphs. The minimum spanning structure of a directed graph is an arborescence, which needs a different algorithm.
Disconnected input
On a disconnected graph the algorithm never reaches V − 1 edges, so the early exit never fires. The loop runs through every edge and returns a minimum spanning forest with V − k edges, where k is the number of components. No code change is needed. A later chapter covers this case in full. For now, if your caller expects a spanning tree, check len(mst) == n - 1 before you trust the result.
Exercises
Exercise
Run Kruskal's algorithm by hand on edges (2, 0, 1), (2, 1, 2), (2, 0, 2), (1, 2, 3) with n = 4, using Python's tuple ordering. List the accepted edges in order, the rejected edges, and the total weight.
Show answer
The sorted order is (1, 2, 3), (2, 0, 1), (2, 0, 2), (2, 1, 2). The algorithm accepts 2–3 (weight 1), then 0–1 (weight 2), then 0–2 (weight 2). That makes 3 = n − 1 edges, so it stops before examining (2, 1, 2). Nothing is explicitly rejected, and the total is 5. Without the early break, (2, 1, 2) would be rejected because 1 and 2 are already connected through 0.
Exercise
A colleague replaces the disjoint set with a set called touched. An edge is accepted unless both endpoints are already in touched. Give a four-vertex input where this returns the wrong answer, and explain why.
Show answer
Use edges (1, 0, 1), (1, 2, 3), (5, 1, 2) with n = 4. The first two edges are accepted, so all four vertices are now touched. The edge 1–2 is rejected even though it is the only link between {0,1} and {2,3}. The result has 2 edges instead of 3 and is not spanning. Being touched does not mean being in the same component.
Exercise
Your graph has V = 10^6 vertices, E = 5·10^6 edges, and integer weights between 0 and 255. Which phase dominates Kruskal's running time, and how could you speed it up?
Show answer
The comparison sort, at O(E log E), dominates. Because the weights fall in a small integer range, a counting sort or bucket sort orders the edges in O(E + 256) time. The total cost then drops to O(E α(V)), which is almost linear.