Experiment 5 - Minimum spanning tree, Kruskal’s algorithm using Greedy
method and analyze it.
Learning Objective: Student should be able to find Minimum Spanning Tree using Kruskal’s
Algorithm of greedy approach.
Tools: C/C++/Java/Python under Windows or Linux environment.
Theory: Develop a code for Minimum Spanning Tree using Kruskal’s Algorithm of greedy
approach
Kruskal's algorithm is an algorithm in graph theory that finds a minimum spanning tree for a
connected weighted graph. This means it finds a subset of the edges that forms a tree that
includes every vertex, where the total weight of all the edges in the tree is minimized. If the
graph is not connected, then it finds a minimum spanning forest (a minimum spanning tree for
each connected component). Kruskal's algorithm is an example of a greedy algorithm. In
Kruskal’s algorithm
• The edges are considered in the non-decreasing order.
• To get the minimum cost spanning tree, the set of edges so far considered may not be a
tree.
T will be a forest since the set of edges T can be completed into a tree iff there are no cycles in
T.
Example of Kruskal’s Algorithm
ALGORITHM:
Algorithm Kruskal (E, cost, n, t)
//E is the set of edges in G. G has n vertices cost (u, v) is the cost of edge (u , v) t is //the set
of edges in the minimum cost spanning tree and mincost is the cost. The //final cost is
returned.
{
Construct the heap out of the edges cost using Heapify;
for i:=1 to n do Parent -1 //Each vertex is in the different set i
mincost 0;
While (i < n -1) and (heap not empty) do
{ delete a minimum cost edge (u,v) from the heap and
reheapify using ADJUST;
J FIND (u); k FIND (v);
If j ≠ k then i i+1
{ T(i, 1) u; T (i,2) v; Mincost mincost
+ cost(u,v);
union (j, k);
}
}
if (i ≠ n-1) then write(“no spanning tree”);
else return minsort; }
ADVANTAGE:
• being able to create MSTs for disconnected graphs (components)
• achieving O(E log V) complexity using a straightforward heap data structure while
Prim’s requires more complex Fibonacci heaps
• faster finding an MST for sparse graphs (but Prim’s works better with dense graphs)
• Kruskal’s works on disjoint-set data structure, so it functions with disconnected graph as
well.
DISADVANTAGES: No disadvantages.
CODE:
Class kruskalmst:
Class Edge:
Def __init__(self, src, dest, weight):
Self.src = src
Self.dest = dest
Self.weight = weight
Def __lt__(self, other):
Return self.weight < other.weight
Class Subset:
Def __init__(self):
Self.parent = None
Self.rank = 0
Def __init__(self, v, e):
Self.V = v
Self.E = e
Self.edges = [None] * e
Def find(self, subsets, i):
If subsets[i].parent != i:
Subsets[i].parent = self.find(subsets, subsets[i].parent)
Return subsets[i].parent
Def union(self, subsets, x, y):
Rootx = self.find(subsets, x)
Rooty = self.find(subsets, y)
If subsets[rootx].rank < subsets[rooty].rank:
Subsets[rootx].parent = rooty
Elif subsets[rootx].rank > subsets[rooty].rank:
Subsets[rooty].parent = rootx
Else:
Subsets[rooty].parent = rootx
Subsets[rootx].rank += 1
Def kruskalmst(self):
Result = [None] * (self.V - 1) # The MST will have V-1 edges
E=0
I=0
# Sort the edges by weight
Self.edges.sort()
# Create subsets for union-find
Subsets = [self.Subset() for _ in range(self.V)]
For j in range(self.V):
Subsets[j].parent = j
# Process edges and add to MST if they don't form a cycle
While e < self.V - 1 and i < self.E:
Next_edge = self.edges[i]
I += 1
X = self.find(subsets, next_edge.src)
Y = self.find(subsets, next_edge.dest)
If x != y:
Result[e] = next_edge
E += 1
Self.union(subsets, x, y)
# If the graph is disconnected and no MST can be formed
If e != self.V - 1:
Print("The graph is disconnected. No MST exists.")
Return
# Print the MST
Print("\nmst Edges:")
Min_cost = 0
For edge in result:
Print(f"{edge.src} - {edge.dest} : {edge.weight}")
Min_cost += edge.weight
Print(f"Total cost of MST: {min_cost}")
Def main():
While True:
Print("\nmenu:")
Print("1. Input Graph")
Print("2. Find Minimum Spanning Tree (MST)")
Print("3. Exit")
Choice = int(input("Enter your choice: "))
If choice == 1:
V = int(input("Enter number of vertices: "))
E = int(input("Enter number of edges: "))
Graph = kruskalmst(V, E)
Print("Enter edges in the format (src dest weight): ")
For i in range(E):
Src, dest, weight = map(int, input().split())
Graph.edges[i] = kruskalmst.Edge(src, dest, weight)
Print("Graph input successful!!")
Elif choice == 2:
If 'graph' not in locals():
Print("Please input graph first!!")
Else:
Graph.kruskalmst()
Elif choice == 3:
Print("Exiting...")
Break
Else:
Print("Invalid choice. Please try again.")
If __name__ == "__main__":
Main()
OUTPUT:
-' 'c:\Users\TCET\Desktop\ritesh aids 59\mst.py'
MENU:
1. Input Graph
2. Find Minimum Spanning Tree (MST)
3. Exit
Enter your choice: 1
Enter number of vertices: 4
Enter number of edges: 5
Enter edges in the format (src dest weight):
016
029
032
124
138
Graph input successful!!
MENU:
1. Input Graph
2. Find Minimum Spanning Tree (MST)
3. Exit
Enter your choice: 2
MST Edges:
0-3:2
1-2:4
0-1:6
Total cost of MST: 12
ANALYSIS:
Time Complexity:
______________________________________________________________________________
______________________________________________________________________________
______________________________________________________________________________
______________________________________________________________________________
______________________________________________________________________________
Space Complexity:
______________________________________________________________________________
______________________________________________________________________________
____________________________________________________________________________
____________________________________________________________________________
APPLICATIONS:
• Minimum spanning trees were first studied for ways to lay out electrical networks in a
way that minimizes the total cost of the wiring. In a minimum spanning tree, all the nodes
(houses) would be connected to power by wires in a way that has minimum cost and
redundancy (cutting any wire necessarily cuts the power grid into two pieces).
• Minimum spanning trees have also been used to generate mazes
• The Christofides algorithm for finding approximate solutions to the Traveling Salesman
uses it in a key step
Learning Outcome: The student should have the ability to understand and apply MST concept
using Kruskal’s algorithm.
Course Outcomes: Upon completion of the course students will be able to apply greedy strategy
to given data.
Conclusion:
______________________________________________________________________________
______________________________________________________________________________
______________________________________________________________________________
______________________________________________________________________________
For Faculty Use
Correction Formative Timely Attendance /
Parameters Assessmen completion Learning
t [40%] of Practical Attitude
[ 40%] [20%]
Marks
Obtained