Union-Find

Union-Find is a method for combining sets together extremely quickly (amortized constant time). Every set has a "leader" that uniquely identifies that set. For instance, if you have two sets {1,3,7,8} and {2,4,5,6}, the set leaders might be 3 and 6. Set leadership is arbitrary. Any element in a set can potentially be the leader.

Union-Find consists of the following two functions:

The union(x,y) method joins the set containing x with the set containing y.

The find(x) method returns the leader of the set containing x.

Both of these functions run in amortized constant time.

There is also an array, p[], where p[i] is the current parent of i (not necessarily i's set leader). This array should never be accessed directly. Use find(x) if you want to know what set x belongs to.

Java
static int[] p; static int n; //n is the number of elements public static void init { 	for(int i=0;i &lt; n;i++) p[i] = i; //Initially, every element belongs to its own set } public static void union(int x, int y) { int xroot = find(x); int yroot = find(y); p[xroot] = yroot; } public static int find(int x) { if(p[x] == x) 		return x; 	p[x] = find(p[x]); return p[x]; }