Subjective_Assignment_3
Subjective_Assignment_3
Prim's Algorithm
import time
import random
# Find the minimum weight edge from visited vertices to unvisited vertices
for i in range(num_vertices):
if visited[i]:
for j in range(num_vertices):
if not visited[j] and graph[i][j] != 0:
if min_edge is None or graph[i][j] < graph[min_edge[0]][min_edge[1]]:
min_edge = (i, j)
if min_edge is None:
break
u, v = min_edge
min_spanning_tree.append((u, v))
visited[v] = True
return min_spanning_tree
Execution Time of
No. of Edges Kruskal's Algorithm (in
Subsets of minimum spanning tree graph
(m) secs)
Kruskal's Algorithm
import time
class UnionFind:
def __init__(self, vertices):
self.parent = {v: v for v in vertices}
self.rank = {v: 0 for v in vertices}
if root1 != root2:
if self.rank[root1] < self.rank[root2]:
self.parent[root1] = root2
elif self.rank[root1] > self.rank[root2]:
Approx.
Execution Time
(In Secs)
9.4652
0.0001
9.8705
0.0001
0.0002
0.0001
0.0001
0.0001
0.0001
0.0002
0.0004
0.0003
0.0002
0.0003
0.0002
0.0002
0.0001
0.0002
0.0002
0.0003
Execution Time of
Number of Execution Time of Kruskal's
Prims Algorithm (in
Execution Algorithm (in secs) 19
secs) 17
15
1 0.000018 9.4652 13
11
2 0.000088 0.0001
9
3 0.000159 9.8705 7
3 0.000365 0.0001 5
3
4 0.0007 0.0002 1
5 0.001242 0.0001 1 2 3
6 0.003339 0.0001 Number of Execution 1 2 3
Both algorithms have their own advantages. Here are their time complexities.
Kruskal:
O(E lgV) - considering you are using union-by-rank and path-compression heuristics for the disjoint-set forest
implementation.
Prim:
Now, let us compare the running times. First state them both in terms of vertices. For dense graph, say, E~V^2 :
Prim: O(V^2)
So, if you have a dense graph with more edge-to-vertex ratio go for Prim's
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15
1 2 3 3 4 5 6 7 8 9 10 11 12 13 14
0.000018 0.000088 0.000159 0.000365 0.0007 0.001242 0.003339 0.003975 0.004099 0.004753 0.006427 0.009677 0.015125 0.014194 0.029004 0.0
9.4652 0.0001 9.8705 0.0001 0.0002 0.0001 0.0001 0.0001 0.0001 0.0002 0.0004 0.0003 0.0002 0.0003 0.0002 0
disjoint-set forest
13 14 15 16 17 18 19 20
12 13 14 15 16 17 18 19
0.015125 0.014194 0.029004 0.021192 0.030651 0.045322 0.091188 0.042485