4
我是新來的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