Reputation: 1
I've recently been studying the Princeton Algorithms course on Coursera. The course begins by teaching an algorithm called Quick-Union to solve the Dynamic Connectivity Problem..
While I understand the purpose and implementation of the algorithm - I'm unable to understand how the root function works in the code provided below. I have provided the class and the main method for my implementation.
public class QuickUnionUF {
private int[] id;
public QuickUnionUF(int N) {
id = new int[N];
for(int i = 0; i < N; i++) {
id[i] = i;
}
}
public int root(int k) {
while(k != id[k]) { k = id[k]; }
return k;
}
public boolean connected(int p, int q) {
return root(p) == root(q);
}
public void union(int p, int q) {
int i = root(p);
int j = root(q);
id[i] = j;
}
public void print() {
System.out.println("Indicies: 0 1 2 3 4 5 6 7 8 9");
System.out.print("Elements: ");
for(int i = 0; i < id.length; i++) {
System.out.print(id[i] + " ");
}
}
//Main Method
public static void main(String[] args) {
QuickUnionUF array = new QuickUnionUF(10);
array.union(2, 9);
array.union(3, 4);
array.union(4, 9);
array.union(5, 6);
System.out.println("\n The root of 3 is " + array.root(3));
}
//The union commands produce the following array: {0 1 9 4 9 6 6 7 8 9}
Output for the root of 3 The root of 3 is 9
I've arranged my array in such a way that it matches the array that the instructor is using, which is why I did those specific union commands. However, I cannot possibly understand why the root of 3 returns 9. Graphically, it makes sense, but the root method simply expresses:
while the number passed as a parameter doesn't equal the element it references, change the number entered (the index) to the element it references.
I believe the root method does this once for root(3). It seems to be only 1 iteration and simply returns 9. How did this happen? Shouldn't k (3) be set to id[k] (4) and then simply return 4 since now k = id[k]? It returns 9.. I used the debugger for some insight but couldn't come to a sound conclusion. There was another StackOverflow post on the exact question, but I didn't find that particularly insightful.
Upvotes: 0
Views: 12