Kruskal’s Algorithm (Simple Implementation for Adjacency Matrix)
Below are the steps for finding MST using Kruskal’s algorithm
- Sort all the edges in non-decreasing order of their weight.
- Pick the smallest edge. Check if it forms a cycle with the spanning tree formed so far. If cycle is not formed, include this edge. Else, discard it.
- Repeat step#2 until there are (V-1) edges in the spanning tree.
We have discussed one implementation of Kruskal’s algorithm in previous post. In this post, a simpler implementation for adjacency matrix is discussed.
Edge 0:(0, 1) cost:2 Edge 1:(1, 2) cost:3 Edge 2:(1, 4) cost:5 Edge 3:(0, 3) cost:6 Minimum cost= 16
The time complexity of Kruskal’s algorithm using the Union-Find algorithm for finding the cycle and sorting the edges is O(E log E + E log V), where E is the number of edges and V is the number of vertices in the graph.
The space complexity of the program is O(V), where V is the number of vertices in the graph.
Note that the above solution is not efficient. The idea is to provide a simple implementation for adjacency matrix representations. Please see below for efficient implementations.
Kruskal’s Minimum Spanning Tree Algorithm | Greedy Algo-2
Kruskal’s Minimum Spanning Tree using STL in C++
Please Login to comment...