Union-find approach - quick-find
- The data structure for this approach is as follows:
- integer array
id[N]Nis equal to the number of objects in the disjoint set- each index of
id[]corresponds to an object in the disjoint set
- each index of
- each value in
id[]denotes the root/representative element of the set/component containing that particular object
- interpretation:
pandqare connected if and only if they have the sameid
- integer array
id[10]{0, 1, 1, 8, 8, 0, 0, 1, 8, 8}
// connected sets:
// {0, 5, 6}
// {1, 2, 7}
// {3, 4, 8, 9}
Find:- Check if
pandqhave the sameid
- Check if
Union:- To merge components containing
pandq, change all entries whoseid==id[p]toid[q]
- To merge components containing
Example implementation
public class QuickFindUF
{
private int[] id;
public QuickFindUF(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];
for (int i = 0; i < id.length; i++)
if (id[i] == pid) id[i] = qid;
}
}
Problem: too slow (algorithm is quadratic)
- for each
newandunion()operation, the array is accessedNtimes (theforloops)- we only use
init()once, butunion()is certainly too expensive:N^2array accesses are required to executeNunion commands onNobjects
- we only use
Cost:
new:NUnion:NFind: 1