-
Notifications
You must be signed in to change notification settings - Fork 3
Expand file tree
/
Copy pathQuickUnionUF.java
More file actions
41 lines (36 loc) · 878 Bytes
/
Copy pathQuickUnionUF.java
File metadata and controls
41 lines (36 loc) · 878 Bytes
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
public class QuickUnionUF
{
// data structure would be an int array
private int[] id;
private int N;
public QuickUnionUF(int N)
{
id = new int[N];
this.N = N;
// put every element in its own connected component
for (int i = 0; i < N; i++)
id[i] = i;
}
// id[i] is root of i if id[i] == i
private int root(int i)
{
// O(N) in worst case
while (i != id[i])
i = id[i];
return i;
}
public boolean connected(int p, int q)
{
// O(N)
// p & q in same component if root is same
return root(p) == root(q);
}
public void union(int p, int q)
{
// O(N)
// make root of p sub-tree of q
int p_root = root(p);
int q_root = root(q);
id[p_root] = q_root;
}
}