MCPcopy Create free account
hub / github.com/Tiwarishashwat/InterviewCodes / DisjointSet

Class DisjointSet

NumberOfOperationsToMakeNetworkConnected.java:22–58  ·  view source on GitHub ↗

Source from the content-addressed store, hash-verified

20}
21
22public class DisjointSet {
23 int parent[];
24 int size[];
25 DisjointSet(int nodes){
26 this.parent = new int[nodes];
27 this.size = new int[nodes];
28 for(int i=0;i<nodes;i++){
29 this.parent[i] = i;
30 this.size[i] = 1;
31 }
32 }
33
34 public int findRootParent(int node){
35 if(node == parent[node]){
36 return node;
37 }
38 parent[node] = findRootParent(parent[node]);
39 return parent[node];
40 }
41 public boolean unionBySize(int node1, int node2){
42 //1. find the root parent
43 int rootParent1 = findRootParent(node1);
44 int rootParent2 = findRootParent(node2);
45 if(rootParent1==rootParent2){
46 return false;
47 }
48 // 2, union of components
49 if(size[rootParent1]<size[rootParent2]){
50 parent[rootParent1] = rootParent2;
51 size[rootParent2] += size[rootParent1];
52 }else {
53 parent[rootParent2] = rootParent1;
54 size[rootParent1] += size[rootParent2];
55 }
56 return true;
57 }
58}
59
60

Callers

nothing calls this directly

Calls

no outgoing calls

Tested by

no test coverage detected