Analysis and Design of Algorithms
PRACTICAL - 5
AIM:- Implementation of Minimum Spanning Tree. Kruskal’s
Algorithm and Prim’s Algorithm.
1. Implementation of Minimum Spanning Tree. Kruskal’s Algorithm.
Code:
def find(parent, i):
while parent[i] != i:
i = parent[i]
return parent[i]
def union(parent, rank, x, y):
if rank[x] < rank[y]:
parent[x] = y
elif rank[x] > rank[y]:
parent[y] = x
else:
parent[y] = x
rank[x] += 1
def KruskalMST(vertices, edges):
result = []
i=0
e=0
edges = sorted(edges, key=lambda item: item[2])
parent = []
rank = []
230169 1
Analysis and Design of Algorithms
for node in range(vertices):
[Link](node)
[Link](0)
while e < vertices - 1:
u, v, w = edges[i]
i=i+1
x = find(parent, u)
y = find(parent, v)
if x != y:
e=e+1
[Link]([u, v, w])
union(parent, rank, x, y)
minimumCost = 0
print("Edges in the MST")
for u, v, weight in result:
minimumCost += weight
print("%d -- %d == %d" % (u, v, weight))
print("Cost of Minimum Spanning Tree = ", minimumCost)
return result
vertices = 6
edges = [(1,2,5), (2,3,1), (0,1,2), (2,1,15), (3,1,10), (5,0,13), (4,1,9)]
print(edges)
230169 2
Analysis and Design of Algorithms
result = KruskalMST(vertices, edges)
print(result)
Output:
[(1, 2, 5), (2, 3, 1), (0, 1, 2), (2, 1, 15), (3, 1, 10), (5, 0, 13), (4, 1, 9)]
Edges in the MST
2 -- 3 == 1
0 -- 1 == 2
1 -- 2 == 5
4 -- 1 == 9
5 -- 0 == 13
Cost of Minimum Spanning Tree = 30
[[2, 3, 1], [0, 1, 2], [1, 2, 5], [4, 1, 9], [5, 0, 13]]
Analysis:
An algorithm that builds the MST by sorting all edges and adding them one by one, ensuring no cycles are formed
using a disjoint-set (union-find) data structure.
Time Complexity: O(E*log(E))
Space Complexity: O(E+V)
230169 3
Analysis and Design of Algorithms
2. Implementation of Minimum Spanning Tree. Prim’s Algorithm.
Code:
def primsmst(graph, vartices):
mst = []
in_mst = [False] * vartices
key = [float('inf')] * vartices
key[0] = 0
parent = [-1] * vartices
for _ in range(vartices):
min_key = float('inf')
u = -1
for v in range(vartices):
if not in_mst[v] and key < min_key:
min_key = key[v]
u=v
in_mst[u] = True
if parent[u] != -1:
[Link]([parent[u], u, key[u]])
for v, weight in graph[u]:
if not in_mst[v] and weight < key[v]:
key[v] = weight
parent[v] = u
return mst
vertices = 6
graph = [(1,2,5), (2,3,1), (0,1,2), (2,1,15), (3,1,10), (5,0,13), (4,1,9)]
230169 4
Analysis and Design of Algorithms
print(graph)
mst = primsmst(graph, vertices)
print(mst)
Output:
[(1, 2, 5), (2, 3, 1), (0, 1, 2), (2, 1, 15), (3, 1, 10), (5, 0, 13), (4, 1, 9)]
Edges in the MST
2 -- 3 == 1
0 -- 1 == 2
1 -- 2 == 5
4 -- 1 == 9
5 -- 0 == 13
Cost of Minimum Spanning Tree = 30
[[2, 3, 1], [0, 1, 2], [1, 2, 5], [4, 1, 9], [5, 0, 13]]
Analysis:
An algorithm that builds the MST by starting from a single vertex and adding the smallest edge connecting a
vertex in the MST to a vertex outside the MST.
Time Complexity: (V^2 + E) or simply O(V^2) for dense graphs.
Space Complexity: O(V+E)
230169 5