union find in csharp

Here's an implementation of the Union-Find data structure using C#:

main.cs
public class UnionFind
{
    private int[] parent;
    private int[] size;
    
    public UnionFind(int n)
    {
        parent = new int[n];
        size = new int[n];
        for (int i = 0; i < n; i++)
        {
            parent[i] = i;
            size[i] = 1;
        }
    }
    
    public int Find(int p)
    {
        while (p != parent[p])
        {
            parent[p] = parent[parent[p]];
            p = parent[p];
        }
        return p;
    }
    
    public void Union(int p, int q)
    {
        int rootP = Find(p);
        int rootQ = Find(q);
        
        if (rootP == rootQ) return;
        
        if (size[rootP] < size[rootQ])
        {
            parent[rootP] = rootQ;
            size[rootQ] += size[rootP];
        }
        else
        {
            parent[rootQ] = rootP;
            size[rootP] += size[rootQ];
        }
    }
    
    public bool Connected(int p, int q)
    {
        return Find(p) == Find(q);
    }
}
968 chars
51 lines

Usage example:

main.cs
UnionFind uf = new UnionFind(10);

uf.Union(1, 2);
uf.Union(2, 3);
uf.Union(4, 5);
uf.Union(6, 7);
uf.Union(7, 8);
uf.Union(8, 9);

bool connected = uf.Connected(1, 3); // true
177 chars
11 lines

gistlibby LogSnag