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;
}
public int root(int p){
while(p != id[p])
p = id[p];
return p;
}
public int getid(int p){
return id[p];
}
public int getsize(int p){
return sz[p];
}
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");
}
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];
}
}
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();
}
}
问题主要是在show()
函数那里,用两种不同的循环最终打印出来的数组是不一样的,想问下为什么会出现这种情况,谢谢大家~
in
for(int j=0;j<id.length;j++)
j
is an index, but thefor(int ele:id)
inele
is an element, not an index - your name is all named afterele
, which is the abbreviation of element.If your id array is not an int type, it will probably be easier for you to understand.