Related data structure:
Related paradigm:
Related algorithm:
AlgorithmGraphGreedy_AlgorithmMinimum_Spanning_TreeMSTKruskal
Kruskal’s algorithm is a greedy algorithm finds a Minimum Spanning Tree (MST) of an undirected weighted graph. The algorithm iteratively adds lowest-weight edge to the resulting MST that will not form a cycle. The edges are sorted and ADT - Disjoint Set (AKA. Union-Find) data structure is used to detect cycles.
Implementation
The union find data structure is used in this algorithm to efficiently keep track of connected components and detect cycles in a graph.
- Sort all the edges of the graph by their weights in non-decreasing order. (makes it easier to find the minimum weighted edges)
- Iterate over the sorted edges, for each edge, check if adding this edge to the MST forms a cycle. This can be done by checking if the vertices of the edge belong to the same connected component of in the union find data structure. If adding the edge does not form a cycle, add it to the MST and merge the connected components of its vertices in the union find data structure.
- Continue the iteration until all vertices are connected (i.e. until the MST contains edges, where is the number of vertices in the graph) or until all edges have been considered.
- The list of edges accumulated during the algorithm forms the MST.
Time complexity
Optimise performance using rank
Union by rank is one of the way to optimise the performance of the union find data structure. In addition to maintain the parent array, each vertex in the union find data structure also maintains a rank
attribute.
When performing union find operation between two sets, represented by roots or parents parent1
and parent2
, the union by rank heuristic considers the ranks of these parents. The set with lower rank is attached to the set with the higher rank (the set with higher rank’s parent becomes the set with the lower rank’s parent). The rank of a root roughly indicates the number of merges (or unions) that root has undergone.
By attaching smaller set (tree) to larger set (tree), the depth of the tree is minimised. Improves the time complexity of the find()
and union()
operation to .
=== ORIGINAL IMPLEMENTATION ===
Do Union(0, 1)
1 2 3
/
0
Do Union(1, 2)
2 3
/
1
/
0
Do Union(2, 3)
3
/
2
/
1
/
0
=== UNION BY RANK ===
Do Union(0, 1)
1 2 3
/
0
Do Union(1, 2)
1 3
/ \
0 2
Do Union(2, 3)
1
/ | \
0 2 3
Back to parent page:
Reference: