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

Class DisjointSet

KruskalsAlgorithm.java:32–68  ·  view source on GitHub ↗

Source from the content-addressed store, hash-verified

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

Callers

nothing calls this directly

Calls

no outgoing calls

Tested by

no test coverage detected