MCPcopy Create free account
hub / github.com/TheAlgorithms/Java / union

Method union

src/main/java/com/thealgorithms/searches/UnionFind.java:65–82  ·  view source on GitHub ↗

Unites the sets containing elements x and y. Uses union by rank to attach the smaller tree under the larger tree. @param x the first element @param y the second element

(int x, int y)

Source from the content-addressed store, hash-verified

63 * @param y the second element
64 */
65 public void union(int x, int y) {
66 int r0 = find(x);
67 int r1 = find(y);
68
69 if (r1 == r0) {
70 return;
71 }
72
73 // Union by rank
74 if (r[r0] > r[r1]) {
75 p[r1] = r0;
76 } else if (r[r1] > r[r0]) {
77 p[r0] = r1;
78 } else {
79 p[r1] = r0;
80 r[r0]++;
81 }
82 }
83
84 /**
85 * Counts the number of disjoint sets.

Callers 5

testUnionOperationMethod · 0.45
testUnionWithRankMethod · 0.45
testFindOperationMethod · 0.45
testUnionSameSetMethod · 0.45

Calls 1

findMethod · 0.95

Tested by 5

testUnionOperationMethod · 0.36
testUnionWithRankMethod · 0.36
testFindOperationMethod · 0.36
testUnionSameSetMethod · 0.36