-
Notifications
You must be signed in to change notification settings - Fork 0
/
Kruskal_Algorithm.java
80 lines (75 loc) · 2.02 KB
/
Kruskal_Algorithm.java
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
76
77
78
79
80
import java.util.*;
import java.util.ArrayList;
public class Kruskal_Algorithm {
public static class edge implements Comparable<edge>{
int src;
int dest;
int wt;
edge(int s,int d,int w){
this.src = s;
this.dest = d;
this.wt = w;
}
@Override
public int compareTo(edge e2){
return this.wt-e2.wt;
}
}
public static void createGraph(ArrayList<edge>edges){
edges.add(new edge (0,1,10));
edges.add(new edge(0,2,15));
edges.add(new edge(0,3,30));
edges.add(new edge(1,3,40));
edges.add(new edge(2,3,50));
}
static int n = 4;
static int parent[] = new int [n];
static int rank[] = new int [n];
public static void inIt(){
for(int i =0;i<parent.length;i++){
parent[i] = i;
}
}
public static int find(int X){
if(parent[X] == X){
return X;
}
return parent[X]=find(parent[X]);
}
public static void union(int a,int b){
int parA = find(a);
int parB = find(b);
if(rank[parA] == rank[parB]){
parent[parB] = parA;
rank[parA]++;
}
if(rank[parA] > rank[parB]){
parent[parB] = parA;
}else{
parent[parA] = parB;
}
}
public static void Kruskal_Algo(ArrayList<edge>edges,int v){
Collections.sort(edges);
int mstCost = 0;
int count = 0;
for(int i=0;count<v-1;i++){
edge e = edges.get(i);
// e.src , e.dest , e.wt
int parA = find(e.src);
int parB = find(e.dest);
if(parA!=parB){ // to check for cycles;
mstCost+=e.wt;
count++;
}
}
System.out.println(mstCost);
}
public static void main(String arg[]){
inIt();
int v = 4;
ArrayList<edge>edges = new ArrayList<>();
createGraph(edges);
Kruskal_Algo(edges,v);
}
}