Skip to content

Union-find approach - quick-find

Union-find approach - quick-find

id[10]{0, 1, 1, 8, 8, 0, 0, 1, 8, 8}

// connected sets:
//  {0, 5, 6}
//  {1, 2, 7}
//  {3, 4, 8, 9}

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)

Cost: