Skip to content

Commit 24ad536

Browse files
committed
Kruskal Algorithm added
1 parent 9f2b675 commit 24ad536

File tree

1 file changed

+102
-0
lines changed

1 file changed

+102
-0
lines changed
Lines changed: 102 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,102 @@
1+
package com.thealgorithms.greedyalgorithms;
2+
3+
import java.util.*;
4+
5+
class Edge implements Comparable<Edge> {
6+
int src, dest, weight;
7+
8+
Edge(int src, int dest, int weight) {
9+
this.src = src;
10+
this.dest = dest;
11+
this.weight = weight;
12+
}
13+
14+
@Override
15+
public int compareTo(Edge other) {
16+
return this.weight - other.weight;
17+
}
18+
}
19+
20+
class DisjointSet {
21+
int[] parent, rank;
22+
23+
DisjointSet(int n) {
24+
parent = new int[n];
25+
rank = new int[n];
26+
for (int i = 0; i < n; i++) {
27+
parent[i] = i;
28+
rank[i] = 0;
29+
}
30+
}
31+
32+
int find(int x) {
33+
if (parent[x] != x) {
34+
parent[x] = find(parent[x]);
35+
}
36+
return parent[x];
37+
}
38+
39+
void union(int x, int y) {
40+
int rootX = find(x);
41+
int rootY = find(y);
42+
43+
if (rootX != rootY) {
44+
if (rank[rootX] < rank[rootY]) {
45+
parent[rootX] = rootY;
46+
} else if (rank[rootX] > rank[rootY]) {
47+
parent[rootY] = rootX;
48+
} else {
49+
parent[rootY] = rootX;
50+
rank[rootX]++;
51+
}
52+
}
53+
}
54+
}
55+
56+
public class KruskalAlgorithm {
57+
58+
public static void main(String[] args) {
59+
Scanner sc = new Scanner(System.in);
60+
61+
System.out.print("Enter number of vertices: ");
62+
int vertices = sc.nextInt();
63+
64+
System.out.print("Enter number of edges: ");
65+
int edgesCount = sc.nextInt();
66+
67+
List<Edge> edges = new ArrayList<>();
68+
69+
System.out.println("Enter edges (src dest weight):");
70+
for (int i = 0; i < edgesCount; i++) {
71+
int src = sc.nextInt();
72+
int dest = sc.nextInt();
73+
int weight = sc.nextInt();
74+
edges.add(new Edge(src, dest, weight));
75+
}
76+
77+
Collections.sort(edges);
78+
79+
DisjointSet ds = new DisjointSet(vertices);
80+
List<Edge> mst = new ArrayList<>();
81+
82+
for (Edge edge : edges) {
83+
int root1 = ds.find(edge.src);
84+
int root2 = ds.find(edge.dest);
85+
86+
if (root1 != root2) {
87+
mst.add(edge);
88+
ds.union(root1, root2);
89+
}
90+
}
91+
92+
System.out.println("\nMinimum Spanning Tree:");
93+
int totalWeight = 0;
94+
for (Edge e : mst) {
95+
System.out.println(e.src + " -- " + e.dest + " == " + e.weight);
96+
totalWeight += e.weight;
97+
}
98+
99+
System.out.println("Total Weight = " + totalWeight);
100+
sc.close();
101+
}
102+
}

0 commit comments

Comments
 (0)