我是java的新手,我有一个加权联合查找算法。当我在剪贴簿页面上的eclipse中运行此代码时,它会一直评估。
java代码
public class weightedUF {
private int[] id;
private int[] sz;
public weightedUF(int N) {
id = new int[N];
sz = new int[N];
for (int i = 0; i < N; i++) {
id[i] = i;
}
for (int i = 0; i < N; i++) {
sz[i] = 1;
}
}
private int root(int i) {
while (i != id[i]) {
i = id[i];
}
return i;
}
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);
if (sz[i] < sz[j]) {
id[i] = j;
sz[j] += sz[i];
}
else {
id[j] = i;
sz[i] += sz[j];
}
id[i] = j;
}
}
剪贴簿测试代码
weightedUF union = new weightedUF(10);
union.union(9, 2);
union.union(5, 2);
union.union(1, 8);
union.union(5, 7);
union.union(4, 3);
union.union(0, 7);
union.union(1, 3);
union.union(2, 4);
union.union(8, 6);
union
答案 0 :(得分:4)
我认为你应该删除你的最后一行:
id[i] = j;
它破坏了你的id数组。