Kruskal's Algorithm
Kruskal’s algorithm builds an MST by processing edges in non-decreasing weight order, adding an edge if it connects two different trees in the growing forest. It uses a disjoint-set data structure to track components efficiently.
Algorithm
KRUSKAL(G, w):
A = empty set
for each vertex v in G.V:
MAKE-SET(v)
sort edges of G.E into non-decreasing order by weight w
for each edge (u, v) in sorted order:
if FIND-SET(u) != FIND-SET(v):
A = A union {(u, v)}
UNION(u, v)
return A
Each vertex starts in its own set. When an edge is selected, the two sets (trees) are merged via UNION. An edge is rejected if its endpoints are already in the same set (would create a cycle).
Correctness
At any iteration, is a forest. The cut , where is the component containing , respects . Since edges are processed in non-decreasing weight, is the lightest edge crossing this cut at the time of consideration (any lighter edge would have been processed earlier and either added or rejected because its endpoints were in different components then but the same component now). By the safe-edge theorem, is safe.
Running Time
- Initialisation of disjoint sets:
- Sorting edges: , since implies
- Processing edges: calls to FIND-SET and at most calls to UNION. With union-by-rank and path compression, each near , where is the inverse Ackermann function (effectively constant, for any practical input)
Total: , dominated by sorting.
Kruskal is optimal for sparse graphs where .
Worked Example
Graph with vertices and edges (weight):
A-B: 4, A-C: 1, B-C: 3, B-D: 2
C-D: 5, C-E: 6, D-E: 7, D-F: 4, E-F: 3
Sorted edges: , , , , , , , , .
Processing:
- : different sets, add. Components:
- : different sets, add. Components:
- : different sets, add (connects and ). Components:
- : different sets, add. Components:
- : same set (both in ), skip
- : different sets, add. Components:
- , terminate. (Remaining edges skipped.)
MST edges: , , , , . Total weight: .
Comparison with Prim
| Aspect | Kruskal | Prim |
|---|---|---|
| Strategy | Forest of trees, merge by edges | Single tree, grow by vertices |
| Data structure | Disjoint-set | Priority queue |
| Complexity | (binary heap) | |
| Best for | Sparse graphs | Dense graphs |
| Edge sorting required | Yes | No |
Summary
| Step | Detail |
|---|---|
| Sort | |
| Disjoint-set ops | amortised each (inverse Ackermann) |
| Edge selection | Greedy, always picks lightest safe edge |
| Total | |
| Termination | Stop when |
Past Tripos: y2024p2q7, y2023p1q9.