-
Notifications
You must be signed in to change notification settings - Fork 7
/
Copy pathKruskal's Algorithm using Union - Find
55 lines (45 loc) · 1.65 KB
/
Kruskal's Algorithm using Union - Find
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
public class Main {
static int[] parent;
public static void main(String[] args) {
int noOfVertices = 5;
parent =new int[noOfVertices];
for(int i=0;i<noOfVertices;i++){
parent[i]=i;
}
List<int[]> adj=new ArrayList<>();
//int[] = {source, destination, weight}
adj.add(new int[]{0,1,4});
adj.add(new int[]{0,2,1});
adj.add(new int[]{1,2,2});
adj.add(new int[]{1,4,5});
adj.add(new int[]{2,3,4});
adj.add(new int[]{3,4,3});
int edgeCount=0;
System.out.println("MST formed by edges :");
while(edgeCount<noOfVertices-1){
int min=Integer.MAX_VALUE;
int[] minEdge=new int[3];
for(int[] edge:adj){
// Checking if cycle Exists or not
if(find(edge[0])!=find(edge[1]) && min>edge[2]){
minEdge=edge;
min=edge[2];
}
}
union(minEdge[0],minEdge[1]);
System.out.println((char)(minEdge[0]+'A')+" - "+(char)(minEdge[1]+'A')+" --> "+minEdge[2]);
edgeCount++;
}
}
static int find(int i){
while(parent[i]!=i){
i=parent[i];
}
return i;
}
static void union(int a,int b){
int x=find(a);
int y=find(b);
parent[x]=parent[y];
}
}