public class WeightedQuickUnionUF {
private int[] id;
private int[] sz;
public WeightedQuickUnionUF(int N){
id = new int[N];
sz = new int[N];
for(int i=0;i<N;i++)
id[i] = i;
for(int j=0;j<N;j++)
sz[j] = 1;
}
// find the root of that number
public int root(int p){
while(p != id[p])
// // Follow links to find a root.
p = id[p];
return p;
}
public int getid(int p){
return id[p];
}
public int getsize(int p){
return sz[p];
}
// print the array
// I use 2 ways to print the final array, but the results are different
public void show(){
for(int ele:id)
System.out.print(id[ele]+ " ");
for(int j=0;j<id.length;j++)
System.out.print(id[j]+ " ");
System.out.print("\n");
}
// link two trees, the root of the smaller one will be linked to the
// root of the larger one
public void union(int p, int q){
int rootp = root(p);
int rootq = root(q);
if(sz[rootp] < sz[rootq]){
id[rootp] = rootq;
sz[rootq] += sz[rootp];
}
else{
id[rootq] = rootp;
sz[rootp] += sz[rootq];
}
}
// test the class I have defined
public static void main(String args[]){
WeightedQuickUnionUF test1 = new WeightedQuickUnionUF(10);
test1.union(6, 0);
test1.union(1, 7);
test1.union(7, 9);
test1.union(8, 9);
test1.union(8, 5);
test1.union(4, 2);
test1.union(9, 3);
test1.union(4, 0);
test1.union(3, 0);
test1.show();
}
}
My Problem is about the performance of the function show(). I use 2 methods to print the same array but the results are different. The correct output of this code should be 6 1 4 1 1 1 4 1 1 1, which means that the for loop can give me the right answer. But the for each loop just can't do the right thing.
eleinstead ofid[ele]