September 2019
Intermediate to advanced
816 pages
18h 47m
English
The union operation begins by fetching the root elements of the given subsets. Furthermore, if these two roots are different, they need to rely on their rank to decide which one will become the parent of the other one (the bigger rank becomes a parent). If they have the same rank, then choose one of them and increase its rank by 1:
public void union(int x, int y) { int xRoot = find(x); int yRoot = find(y); if (xRoot == yRoot) { return; } if (rank[xRoot] < rank[yRoot]) { parent[xRoot] = yRoot; } else if (rank[yRoot] < rank[xRoot]) { parent[yRoot] = xRoot; } else { parent[yRoot] = xRoot; rank[xRoot]++; }}
OK. Let's now define a disjoint set:
DisjointSet set = new DisjointSet(11);set.union(0, 1);set.union(4, ...