Skip to content

Commit f238846

Browse files
williamfisetclaude
andauthored
Refactor UnionFind: rename id to parent, use recursive find (#1305)
Rename the `id` array to `parent` for clarity and switch the iterative find implementation to the recursive path-compression variant. Co-authored-by: Claude Opus 4.6 <noreply@anthropic.com>
1 parent b71af5a commit f238846

1 file changed

Lines changed: 8 additions & 23 deletions

File tree

  • src/main/java/com/williamfiset/algorithms/datastructures/unionfind

src/main/java/com/williamfiset/algorithms/datastructures/unionfind/UnionFind.java

Lines changed: 8 additions & 23 deletions
Original file line numberDiff line numberDiff line change
@@ -27,8 +27,8 @@ public class UnionFind {
2727
// Used to track the size of each component
2828
private int[] sz;
2929

30-
// id[i] points to the parent of i, if id[i] = i then i is a root node
31-
private int[] id;
30+
// parent[i] points to the parent of i, if parent[i] = i then i is a root node
31+
private int[] parent;
3232

3333
// Tracks the number of components in the union find
3434
private int numComponents;
@@ -43,10 +43,10 @@ public UnionFind(int size) {
4343

4444
this.size = numComponents = size;
4545
sz = new int[size];
46-
id = new int[size];
46+
parent = new int[size];
4747

4848
for (int i = 0; i < size; i++) {
49-
id[i] = i; // Link to itself (self root)
49+
parent[i] = i; // Link to itself (self root)
5050
sz[i] = 1; // Each component is originally of size one
5151
}
5252
}
@@ -59,25 +59,10 @@ public UnionFind(int size) {
5959
* @return the root of the component containing p
6060
*/
6161
public int find(int p) {
62-
int root = p;
63-
while (root != id[root]) root = id[root];
64-
65-
// Path compression: point every node along the path directly to root
66-
while (p != root) {
67-
int next = id[p];
68-
id[p] = root;
69-
p = next;
70-
}
71-
72-
return root;
62+
if (p == parent[p]) return p;
63+
return parent[p] = find(parent[p]);
7364
}
7465

75-
// Alternative recursive formulation for find with path compression:
76-
// public int find(int p) {
77-
// if (p == id[p]) return p;
78-
// return id[p] = find(id[p]);
79-
// }
80-
8166
/** Returns true if elements p and q are in the same component. */
8267
public boolean connected(int p, int q) {
8368
return find(p) == find(q);
@@ -114,11 +99,11 @@ public void unify(int p, int q) {
11499
// Merge smaller component into the larger one
115100
if (sz[root1] < sz[root2]) {
116101
sz[root2] += sz[root1];
117-
id[root1] = root2;
102+
parent[root1] = root2;
118103
sz[root1] = 0;
119104
} else {
120105
sz[root1] += sz[root2];
121-
id[root2] = root1;
106+
parent[root2] = root1;
122107
sz[root2] = 0;
123108
}
124109

0 commit comments

Comments
 (0)