Union Find With Path Compression (Java)

Implement a Java disjoint set union find with path compression and union by rank for near constant amortized time.

JavaData Integrity

Code

javasnippet
7 lines
public class UnionFind {
    int[] parent, rank; int count;
    public UnionFind(int n) { parent = new int[n]; rank = new int[n]; for (int i = 0; i < n; i++) parent[i] = i; count = n; }
    public int find(int x) { while (parent[x] != x) { parent[x] = parent[parent[x]]; x = parent[x]; } return x; }
    public boolean union(int a, int b) { int ra = find(a), rb = find(b); if (ra == rb) return false; if (rank[ra] < rank[rb]) parent[ra] = rb; else if (rank[ra] > rank[rb]) parent[rb] = ra; else { parent[rb] = ra; rank[ra]++; } count--; return true; }
    public boolean connected(int a, int b) { return find(a) == find(b); }
}

How the snippet works

Union Find With Path Compression (Java) keeps everything in the class UnionFind and the functions UnionFind, find, union and connected.

Applying it

The main signature reads public UnionFind(int n)

Statements that matter

public int find(int x) { while (parent[x] != x) { parent[x] = parent[parent[x]]; x = parent[x]; } return x; }
public boolean connected(int a, int b) { return find(a) == find(b); }

Interactive Tools for This Topic

FAQ

Does this require external packages?
No. It relies only on built-in language and platform APIs, so you can paste it into a project without installing anything. The file defines `UnionFind`, `find`, `union` at load time.