function kruskal(graph: Graph) {const edges = [...graph.edges].sort((first, second) => first.weight - second.weight);
const unionFind = new UnionFind(graph.nodes.length);
const tree: Edge[] = [];
for (const edge of edges) {if (unionFind.find(edge.from) === unionFind.find(edge.to)) continue;
unionFind.union(edge.from, edge.to);
tree.push(edge);
}
return tree;
}
Sort the 11 edges by weight. Every node starts as its own component (the label is its representative).
Understanding Kruskal
The idea
Kruskal's algorithm sorts every edge by weight and walks the list, accepting an edge whenever its two endpoints are still in different pieces of the forest, and rejecting it when they are already connected, because then it would close a cycle. After V − 1 acceptances the forest is one tree.
The 'already connected' question is answered by a union-find structure: each node points to a representative, find follows the pointers, union merges two sets. With path compression it is almost O(1), so sorting the edges is the whole cost.
The four stages
Complexity
Versus its siblings
Pseudocode
KRUSKAL(graph)
sort edges by weight; every node its own set
for each edge from–to in that order
if find(from) ≠ find(to): union(from, to); add the edge to the tree
When to use
Pitfalls
History
Joseph Kruskal published the algorithm in 1956, one year before Prim, as a proof about the shortest spanning subtree of a graph. The union-find structure that makes it fast was analysed by Tarjan in 1975, who showed its near-constant inverse-Ackermann bound.