The idea of quick union is that if the root ID of object P and the root ID of object q are equal, then p and q are connected.
To connect object p and object q (it is known that the two objects are not connected), set the value of root ID of p to the value of root ID of q, so that the two tree structures of p and q will be merged
Algorithm source code:
public class QuickUnionUF { private int[] id; //Access id[] N times public QuickUnionUF(int size) { id = new int[size]; for (int i = 0; i < size; i++) { //Initialization id [] id[i] = i; } } //Access id[] N times at most 1 time at least private int root(int i) { //Pursue the parent node while (i != id[i]) { i = id[i]; } return i; } //Maximum access id[] N + N - 1 = 2N - 1, minimum access 1 + 1 = 2 //In the least case, if you only access id[] 2 times, the two objects must not be connected public boolean connected(int p, int q) { return root(p) == root(q); } //If p, q are never connected //Then access id[] N times at most and 2 times at least public void union(int p, int q) { int i = root(p); // (N - 1) ~ 1 int j = root(q); // 1 ~ (N - 1) id[i] = j; } public String toString() { String temp = "{"; for (int i = 0; i < id.length; i++) { if (i == id.length - 1) { temp += id[i] + "}"; break; } temp += id[i] + ", "; } return temp; } }
Source code of test class:
public class TestQuickUnion { public static void main(String[] args) { QuickUnionUF qu = new QuickUnionUF(10); //Access array id[] 10 times qu.union(4, 3); System.out.println(qu); //{0, 1, 2, 3, 3, 5, 6, 7, 8, 9} qu.union(3, 8); System.out.println(qu); //{0, 1, 2, 8, 3, 5, 6, 7, 8, 9} qu.union(6, 5); System.out.println(qu); //{0, 1, 2, 8, 3, 5, 5, 7, 8, 9} //Connecting N objects requires access id[] (N - 1) * 2 ~ (N - 1) * N times //The number of accesses to id [] increases with the number of connected objects //The maximum increment is the number of connected objects //The time complexity of union() of the current algorithm is improved //But compared with quick find, its connected() time cost is higher System.out.println(qu.connected(8, 4)); //true System.out.println(qu.connected(5, 4)); //false } }
Quick union is as slow as quick find (the time it takes to process large amounts of data).
Disadvantages of quick find:
1. Time cost of union() is too high (access N array)
2. The tree structure formed by connecting multiple objects is flattened, but when the number of objects to be connected is large, macroscopically, the extension of this flattened tree structure costs a lot of time!
Disadvantages of quick Union:
1. Macroscopically, the tree structure formed by connecting multiple objects may become very tall;
2. find(connected()) takes a lot of time (Access 2 ~ 2N-1 array)