# Union-Find

Quick Find

``````public class QuickFind{
private int[] id;
public QuickFind(int N){
id = new int[N];
for(int i = 0;i < N;i++){
id[i] = i;
}
}

//判断是否相连
public boolean connected(int p,int q){
return id[p]==id[q];
}

//将两点相连
public  void union(int p,int q){
int pid = id[p];
int qid = id[q];
if(pid == qid){
return;
}
for(int i  = 0;i<id.length;i++){
if(id[i] == pid){
id[i] = qid;
}
}
}
}
``````

Quick Union

``````public class QuickFind{
private int[] id;
public QuickFind(int N){
id = new int[N];
for(int i = 0;i < N;i++){
id[i] = i;
}
}

//找根节点
public int root(int q){
while(id[q] != q){
q = id[q];
}
return q;
}

//判断是否相连
public boolean connected(int p,int q){
return root(p)==root(q);
}

//将两点相连
public void union(int p,int q){
id[root(p)] = root(q);
}
}
``````

Quick-Union Improvements

``````public class QuickFind{
private int[] id;
private int[] sz;
public QuickFind(int N){
id = new int[N];
sz = new int[N];
for(int i = 0;i < N;i++){
id[i] = i;
sz[i] = 1;
}
}

//找根节点
public int root(int q){
while(id[q] != q){
q = id[q];
}
return q;
}

//判断是否相连
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(i==j){
return;
}
if(sz[i]<sz[j]){
id[i] =j;
sz[j]+=sz[i];
}else{
idj] = i;
sz[i]+=sz[j];
}
}
}
``````

``````public int root(int q){
while(id[q] != q){
id[q] = id[id[q]];//将该节点加到其祖父节点下
q = id[q];
}
return q;
}
``````

http://visualgo.net/ufds 展示的为最后path compression的做法（搜索根节点时将路径上每个结点加到根节点上）。