-
Notifications
You must be signed in to change notification settings - Fork 0
Expand file tree
/
Copy pathQuickUnionUF.java
More file actions
57 lines (52 loc) · 1.1 KB
/
Copy pathQuickUnionUF.java
File metadata and controls
57 lines (52 loc) · 1.1 KB
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
//O(N^3)
public class QuickUnionUF
{
private int[] id;
/*set id of each object to itself
(N array accesses)*/
public QuickUnionUF(int N)
{
id=new int[N];
for(int i=0;i<N;i++){
id[i]=i;
}
}
/*chase parent pointers until root
(Depth of i array accesses)*/
public int root(int i){
while(i!=id[i])
//id[i]= id[id[i]];
i=id[i];
return i;
}
/*check if p and q have same root
(depth of p and q array accesses)
*/
public boolean connected(int p, int q)
{
return root(p)==root(q);
}
/*change root of p to point to root of q
(depth of p and q array accesses)
*/
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
{
id[j]=i;
sz[i]+=sz[j]
}
*/
id[i]=j;
}
}