How it works?
Lesson 3 of 9 in Coddy's Kruskal's Algorithm - Graph Algorithms course.
Union-find keeps a parent array. Each vertex starts as its own root. Two operations drive everything:
- find(x): follow
parentlinks until you reach a root (a vertex that is its own parent). Two vertices are connected when they share a root. - union(a, b): point one root at the other, merging the two sets.
Kruskal's Algorithm:
- Process edges from smallest weight to largest.
- For each edge,
findthe roots of its endpoints. If they differ, the edge joins two separate pieces:unionthem and add its weight to the total. - If the roots are the same, the edge would form a cycle, so skip it.
After processing every edge, the chosen edges form the MST (for a connected graph, exactly n - 1 of them).
Try it yourself
This lesson doesn't include a code challenge.
This lesson includes a short quiz. Start the lesson to answer it and track your progress.
All lessons in Kruskal's Algorithm - Graph Algorithms
2The Algorithm
How it works?Pseudo CodeImplementation (Part 1)Implementation (Part 2)