-
Notifications
You must be signed in to change notification settings - Fork 0
Expand file tree
/
Copy pathKruskalAlgorithm.java
More file actions
75 lines (60 loc) · 1.89 KB
/
KruskalAlgorithm.java
File metadata and controls
75 lines (60 loc) · 1.89 KB
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
package graph;
import java.util.ArrayList;
import java.util.Comparator;
public class KruskalAlgorithm {
private static void kruskals(int V, ArrayList<Edge> edges) {
edges.sort(new Comparator<>() {
@Override
public int compare(Edge o1, Edge o2) {
return o1.weight - o2.weight;
}
});
int j = 0;
int noOfEdges = 0;
int[] parent = new int[V];
int[] rank = new int[V];
Edge[] results = new Edge[V];
for (int i = 0; i < V; i++) {
parent[i] = i;
}
while (noOfEdges < V - 1) {
Edge nextEdge = edges.get(j);
int x = findRoot(parent, nextEdge.src);
int y = findRoot(parent, nextEdge.dest);
if (x != y) {
results[noOfEdges] = nextEdge;
union(parent, rank, x, y);
noOfEdges++;
}
j++;
}
int minCost = 0;
for (int i = 0; i < noOfEdges; i++) minCost += results[i].weight;
System.out.println("Total cost of MST: " + minCost);
}
private static void union(int[] parent, int[] rank, int x, int y) {
int rootX = findRoot(parent, x);
int rootY = findRoot(parent, y);
if (rank[rootY] < rank[rootX]) {
parent[rootY] = rootX;
} else if (rank[rootX] < rank[rootY]) {
parent[rootX] = rootY;
} else {
parent[rootY] = rootX;
rank[rootX]++;
}
}
private static int findRoot(int[] parent, int i) {
if (parent[i] == i) return parent[i];
parent[i] = findRoot(parent, parent[i]);
return parent[i];
}
static class Edge {
int src, dest, weight;
public Edge(int src, int dest, int weight) {
this.src = src;
this.dest = dest;
this.weight = weight;
}
}
}