Kruskal's Algorithm
Kruskal's Algorithm
What is Kruskal’s
Algorithm?
Graphs might just be one of the most difficult
areas of programming to approach as a
beginner. This is primarily because questions
of data structures and algorithms in graphs
are not very clear about how to proceed with
a solution. It is only through rigorous practice
that one can improve their knowledge of the
algorithm. As it happens, one of the most
popular algorithms used with graphs is the
ones for traversing the graph in the minimum
time possible as well as the ones which
produce a minimum spanning tree from it.
For graph traversal, we have the BFS and DFS
algorithms, while the equivalent minimum
spanning tree can be produced with the help
of Prim’s algorithm or Kruskal’s algorithm.
What is a Minimum
spanning tree?
The main objective of using Kruskal’s
algorithm is for getting the minimum cost
spanning tree for a graph. However, this
makes no sense if you don’t understand what
a minimum spanning tree exactly is. This can
be the best explaining with an example.
Example
Let’s work out an example. Consider the
above graph and let’s try to apply Kruskal’s
algorithm to it.
#include <iostream>
#include <vector>
#include <algorithm>
int parent(int a)
{
while(root[a] != a)
{
root[a] = root[root[a]];
a = root[a];
}
return a;
}
int main()
{
int x, y;
long long weight, cost, minCost;
for(int i = 0;i < MAX;++i)
{
root[i] = i;
}
p[0] = make_pair(10, make_pair(0, 1));
p[1] = make_pair(18, make_pair(1, 2));
p[2] = make_pair(13, make_pair(2, 3));
p[3] = make_pair(21, make_pair(0, 2));
p[4] = make_pair(22, make_pair(1, 3));
sort(p, p + edges);
minCost = kruskal();
cout << "Minimum cost is: "<< minCost
return 0;
}
Output
The output for the given code segment is:
Conclusion
Our explanation of Kruskal’s algorithm and
how it can be used to find a minimum
spanning tree for a graph should prove to a
useful tool in your preparation. The attached
code also shows an implementation of
Kruskal’s algorithm in C++.
FavTutor - 24x7
Live Coding Help
from Expert Tutors!
Arkadyuti Bandyopadhyay
“ Hi, I am Arkadyuti, a developer and open source
enthusiast with quite some experience in content
writing. I wish to make the switch to a full-stack
developer one day. ”
Convert Dictionary to
Dataframe in Python (with
Examples)
Komal Gupta
•YouTube