Graph AlgosGraph Algorithms

Kruskal's Algorithm

Minimum spanning tree by sorting all edges and greedily adding each edge that joins two different components, tracked with union-find.

Learn Kruskal's Algorithm →
42518103263ABCDEFG
Edges by weight
B–G (1)A–C (2)G–E (2)E–F (3)G–D (3)A–B (4)B–D (5)D–F (6)C–G (8)C–E (10)
DSU parent
nodeparentroot
AAA
BBB
CCC
DDD
EEE
FFF
GGG
1/15Sort the 10 edges by weight and put each node in its own set. Kruskal grows a forest by taking the cheapest edge that joins two different trees.
Edge under considerationAccepted (MST)Rejected (cycle)Node in some tree
1sort edges by weight ascending
2make_set(v) for every node
3for (u, v, w) in edges:
4 if find(u) != find(v):
5 union(u, v); mst.add((u, v, w))
6 else: skipu and v already connected, edge would close a cycle
7return mst
Complexity
best O(E log E)
avg O(E log E)
worst O(E log E)
space O(V + E)
Speed