Skip to content

Commit 8773612

Browse files
Merge pull request #256 from Vijayaa21/main
Create kruskal.py
2 parents 596f381 + 1e3fbe3 commit 8773612

1 file changed

Lines changed: 79 additions & 0 deletions

File tree

Lines changed: 79 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,79 @@
1+
"""
2+
Data Structure: Kruskal's Minimum Spanning Tree (MST) Algorithm
3+
4+
Description:
5+
Kruskal's algorithm finds the Minimum Spanning Tree of a graph by
6+
sorting edges by weight and adding them one by one without creating cycles.
7+
8+
Use Case:
9+
Useful in network design (telecom, computer networks), clustering,
10+
and designing efficient transportation systems.
11+
12+
Time Complexity:
13+
O(E log E), where E = number of edges (due to sorting edges)
14+
15+
Space Complexity:
16+
O(V + E), where V = number of vertices, E = number of edges
17+
"""
18+
19+
class DisjointSet:
20+
"""Union-Find data structure for cycle detection."""
21+
def __init__(self, n):
22+
self.parent = list(range(n))
23+
self.rank = [0] * n
24+
25+
def find(self, x):
26+
if self.parent[x] != x:
27+
self.parent[x] = self.find(self.parent[x])
28+
return self.parent[x]
29+
30+
def union(self, x, y):
31+
xroot, yroot = self.find(x), self.find(y)
32+
if xroot == yroot:
33+
return False
34+
if self.rank[xroot] < self.rank[yroot]:
35+
self.parent[xroot] = yroot
36+
elif self.rank[xroot] > self.rank[yroot]:
37+
self.parent[yroot] = xroot
38+
else:
39+
self.parent[yroot] = xroot
40+
self.rank[xroot] += 1
41+
return True
42+
43+
44+
def kruskal(vertices, edges):
45+
"""
46+
Compute MST using Kruskal's algorithm.
47+
48+
Args:
49+
vertices (int): Number of vertices.
50+
edges (list of tuples): Each tuple = (weight, u, v)
51+
52+
Returns:
53+
list: Edges in the MST
54+
"""
55+
edges.sort()
56+
ds = DisjointSet(vertices)
57+
mst = []
58+
for weight, u, v in edges:
59+
if ds.union(u, v):
60+
mst.append((u, v, weight))
61+
return mst
62+
63+
64+
def main():
65+
"""Test Kruskal's MST algorithm."""
66+
vertices = 4
67+
edges = [
68+
(10, 0, 1),
69+
(6, 0, 2),
70+
(5, 0, 3),
71+
(15, 1, 3),
72+
(4, 2, 3)
73+
]
74+
mst = kruskal(vertices, edges)
75+
print("Edges in MST:", mst)
76+
77+
78+
if __name__ == "__main__":
79+
main()

0 commit comments

Comments
 (0)