In this implementation of Quick Find algorithm, Constructor takes N
steps so does union()
.
The instructor said that union
is too expensive as it takes N^2
to process sequence of N
union
commands on N
objects, How can union
be quadratic when it accesses array elements one at a time?
public class QuickFind
{
private int[] id;
public QuickFind(int N) {
id = new int[N];
for (int i=0; i<N; i++) {
id[i] = i;
}
}
public boolean connected(int p, int q) {
return id[p] == id[q];
}
public void union(int p, int q) {
int pid = id[p];
int qid = id[q];
for (int i=0; i<id.length; i++)
if (id[i] == pid)
id[i] = qid;
}
}
The find() operation traverses up from x to find root. The idea of path compression is to make the found root as parent of x so that we don't have to traverse all intermediate nodes again. If x is root of a subtree, then path (to root) from all nodes under x also compresses. The two techniques complement each other.
You can do n union find (union by rank or size) operations with complexity O(n lg* n) where lg* n is the inverse Ackermann function using path compression optimization.
Each invocation of union
method requires you iterate over the id
array, which takes O(n)
time. If you invoke union
method n
times, then the time required is n*O(n) = O(n^2)
.
You can improve time complexity of union
method to O(1)
, by making the time complexity of connected method higher, probably O(log n)
, but this is just one time operation. I believe that your text book explain this in details.
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With