Implementing the union operation

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, 9);
set.union(6, 5);
set.union(0, 7);
set.union(4, 3);
set.union(4, 2);
set.union(6, 10);
set.union(4, 5);

And now let's play with it:

// is 4 and 0 friends => false
System.out.println("Is 4 and 0 friends: "
+ (set.find(0) == set.find(4)));

// is 4 and 5 friends => true
System.out.println("Is 4 and 5 friends: "
+ (set.find(4) == set.find(5)));

This algorithm can be optimized by compressing the paths between elements. For example, check the following diagram:

On the left-hand side, in trying to find the parent of 5, you must pass through 6 until it reaches 4. Similarly, in trying to find the parent of 10, you must pass through 6 until it reaches 4. However, on the right-hand side, we compress the paths of 5 and 10 by linking them directly to 4. This time, we can find the parent of 5 and 10 without passing through intermediary elements.

Path compression can take place in relation to the find() operation, as follows:

public int find(int x) {

if (parent[x] != x) {
return parent[x] = find(parent[x]);
}

return parent[x];
}

The code bundled to this book contains both applications, with and without path compression.

..................Content has been hidden....................

You can't read the all page of ebook, please click here login for view all page.
Reset
3.137.41.205