Concepts and efficiency of union lookup are not detailed here. There are a lot of things on the web. This is a good place to record the Java code implementation of union lookup.
Three steps:
1. Initialize the pres and rangks arrays, pres is the parent node (the previous level) of each element, ranks is the rank of the tree (the depth of the tree) when each element is the root node, pres is initially set for each element itself, ranks is set for each value to 0.
2.find() queries the first level of the element to do path compression conveniently
3.unionSet() combines two sets and merges them by rank. The root node of a tree with a small rank points to the root node of a tree with a large rank.
//Java implemented union lookup data structure and union lookup algorithm public class And Search Sets { public static void main(String[] args) { int n = 10; //Number of nodes //Edge data int[][] edges = {{0, 9}, {9, 3}, {1, 2}, {2, 8}, {4, 5}, {6, 7}, {0, 5}, {6, 8}}; int[] pres = new int[n]; int[] ranks = new int[n]; //Initialize, set the pres level above each element to itself, and set the ranks depth to 0 for each element for (int i = 0; i < n; i++) { pres[i] = i; ranks[i] = 0; } //Construct and find sets from edge data for (int[] edge : edges) unionSet(edge[0], edge[1], pres, ranks); printAns(pres, ranks); } //And: Merge two sets, merge by rank public static void unionSet(int n1, int n2, int[] pres, int[] ranks) { int root1 = find(n1, pres); int root2 = find(n2, pres); if (ranks[root1] < ranks[root2]) { pres[root1] = root2; } else { pres[root2] = root1; if (ranks[root1] == ranks[root2]) ranks[root1]++; } } //Find: Find the first level of an element public static int find(int x, int[] pres) { int root = x; while (pres[root] != root) root = pres[root]; //Path Compression int p = x; while (pres[p] != p) { int t = pres[p]; pres[p] = root; p = t; } return root; } public static void printAns(int[] pres, int[] ranks) { System.out.print("pres:\t"); for (int pre : pres) System.out.print(pre + " "); System.out.print("\nranks:\t"); for (int rank : ranks) System.out.print(rank + " "); System.out.print("\nidx:\t"); for (int i = 0; i < pres.length; i++) System.out.print(i + " "); } } /* * pres: 0 6 1 0 0 4 6 6 1 0 * ranks:2 1 0 0 1 0 2 0 0 0 * idx: 0 1 2 3 4 5 6 7 8 9 * * */