Docsity

Java Implementation of Quick Union Union-Find Algorithm, Study notes of Algorithms and Programming

Partial preview of the text

Download Java Implementation of Quick Union Union-Find Algorithm and more Study notes Algorithms and Programming in PDF only on Docsity!

import java.util.Scanner;

class QuickUnionUF { int id[];

QuickUnionUF(int n) { id=new int[n]; for(int i=0;i<n;i++) id[i]=i; }

private int root (int i) { while(i!=id[i]) i=id[i]; return i; }

public boolean connected(int a, int b) { return root(a)==root(b); }

public void union(int a,int b) { id[root(a)]=root(b); // Note: The roots have the same id as their index number

}