Skip to content

Commit 8bbb886

Browse files
committed
Add Kruskal's Algorithm implementation
1 parent 2c4bf3c commit 8bbb886

1 file changed

Lines changed: 166 additions & 0 deletions

File tree

Lines changed: 166 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,166 @@
1+
package com.thealgorithms.graph;
2+
3+
import java.util.ArrayList;
4+
import java.util.Collections;
5+
import java.util.List;
6+
7+
/**
8+
* Kruskal's Algorithm for finding Minimum Spanning Tree (MST)
9+
*
10+
* Kruskal's algorithm is a greedy algorithm that finds a minimum spanning tree
11+
* for a connected weighted graph. It works by sorting all edges by weight and
12+
* adding them one by one to the MST if they don't form a cycle.
13+
*
14+
* Time Complexity: O(E log E) where E is the number of edges
15+
* Space Complexity: O(V + E) where V is the number of vertices
16+
*
17+
* @author YourName
18+
*/
19+
public final class KruskalsAlgorithm {
20+
private KruskalsAlgorithm() {
21+
}
22+
23+
/**
24+
* Edge class representing a weighted edge in the graph
25+
*/
26+
static class Edge implements Comparable<Edge> {
27+
int src;
28+
int dest;
29+
int weight;
30+
31+
Edge(int src, int dest, int weight) {
32+
this.src = src;
33+
this.dest = dest;
34+
this.weight = weight;
35+
}
36+
37+
@Override
38+
public int compareTo(Edge other) {
39+
return Integer.compare(this.weight, other.weight);
40+
}
41+
}
42+
43+
/**
44+
* Disjoint Set (Union-Find) data structure
45+
*/
46+
static class DisjointSet {
47+
private final int[] parent;
48+
private final int[] rank;
49+
50+
DisjointSet(int n) {
51+
parent = new int[n];
52+
rank = new int[n];
53+
for (int i = 0; i < n; i++) {
54+
parent[i] = i;
55+
rank[i] = 0;
56+
}
57+
}
58+
59+
/**
60+
* Find the representative (root) of the set containing element x
61+
* Uses path compression for optimization
62+
*/
63+
int find(int x) {
64+
if (parent[x] != x) {
65+
parent[x] = find(parent[x]); // Path compression
66+
}
67+
return parent[x];
68+
}
69+
70+
/**
71+
* Unite two sets containing elements x and y
72+
* Uses union by rank for optimization
73+
*/
74+
void union(int x, int y) {
75+
int rootX = find(x);
76+
int rootY = find(y);
77+
78+
if (rootX == rootY) {
79+
return;
80+
}
81+
82+
// Union by rank
83+
if (rank[rootX] < rank[rootY]) {
84+
parent[rootX] = rootY;
85+
} else if (rank[rootX] > rank[rootY]) {
86+
parent[rootY] = rootX;
87+
} else {
88+
parent[rootY] = rootX;
89+
rank[rootX]++;
90+
}
91+
}
92+
}
93+
94+
/**
95+
* Find Minimum Spanning Tree using Kruskal's Algorithm
96+
*
97+
* @param vertices Number of vertices in the graph
98+
* @param edges List of edges in the graph
99+
* @return List of edges in the Minimum Spanning Tree
100+
*/
101+
public static List<Edge> kruskalMST(int vertices, List<Edge> edges) {
102+
List<Edge> mst = new ArrayList<>();
103+
104+
// Sort edges by weight in ascending order
105+
Collections.sort(edges);
106+
107+
DisjointSet ds = new DisjointSet(vertices);
108+
109+
// Iterate through sorted edges
110+
for (Edge edge : edges) {
111+
int srcRoot = ds.find(edge.src);
112+
int destRoot = ds.find(edge.dest);
113+
114+
// If including this edge doesn't form a cycle, add it to MST
115+
if (srcRoot != destRoot) {
116+
mst.add(edge);
117+
ds.union(srcRoot, destRoot);
118+
119+
// MST is complete when we have V-1 edges
120+
if (mst.size() == vertices - 1) {
121+
break;
122+
}
123+
}
124+
}
125+
126+
return mst;
127+
}
128+
129+
/**
130+
* Calculate total weight of the MST
131+
*
132+
* @param mst List of edges in the Minimum Spanning Tree
133+
* @return Total weight of the MST
134+
*/
135+
public static int getMSTWeight(List<Edge> mst) {
136+
int totalWeight = 0;
137+
for (Edge edge : mst) {
138+
totalWeight += edge.weight;
139+
}
140+
return totalWeight;
141+
}
142+
143+
/**
144+
* Main method for testing
145+
*/
146+
public static void main(String[] args) {
147+
int vertices = 4;
148+
List<Edge> edges = new ArrayList<>();
149+
150+
// Example graph
151+
edges.add(new Edge(0, 1, 10));
152+
edges.add(new Edge(0, 2, 6));
153+
edges.add(new Edge(0, 3, 5));
154+
edges.add(new Edge(1, 3, 15));
155+
edges.add(new Edge(2, 3, 4));
156+
157+
List<Edge> mst = kruskalMST(vertices, edges);
158+
159+
System.out.println("Edges in the Minimum Spanning Tree:");
160+
for (Edge edge : mst) {
161+
System.out.println(edge.src + " -- " + edge.dest + " : " + edge.weight);
162+
}
163+
164+
System.out.println("\nTotal weight of MST: " + getMSTWeight(mst));
165+
}
166+
}

0 commit comments

Comments
 (0)