Quick Find(eager approach)
Data Structure
-Integer Array id[] of size N
-Interpretation: p and q are connected iff they have the same id
Example
Find
connected( p, q )
Check if p and q have the same id
Union
union( p, q )
To merger component containing p and q, change all entries whose id equals id[p] to id[q](a lot of entries whose value may be changed)
Quick Find Implementation
public class QuickFindUF
{
private int[] id;
public QuickFindUF( int N )
{
id = new int[N];
for( int i = 0 ; i < N; i++ )
{
// Set id of each object to itself(N accesses)
id[i] = i;
}
}
public boolean connected( int p, int q )
{
// Check if p and q are connected(2 accesses)
return id[p] == id[q];
}
public void union( int p, int q )
{
// Change all entries with id[p] to id[q]( at most 2N+2 accesses)
int pid = id[p],
qid = id[q];
for( int i = 0; i < id.length; i++ )
{
if( id[i] == pid )
{
id[i] = qid;
}
}
}
}
Cost
Algorithm | initialize | union | find |
---|---|---|---|
quick-find | O(N) | O(N) | O(1) |
Union is too expansive!!!
Quadratic time algorithms are too slow, because they don’t scale with the technology.