Skip to content

Instantly share code, notes, and snippets.

@iamakimmer
Created February 16, 2013 03:50
Show Gist options
  • Save iamakimmer/4965456 to your computer and use it in GitHub Desktop.
Save iamakimmer/4965456 to your computer and use it in GitHub Desktop.
Quick Find Weighed Union
public class QuickFindWeighted
{
private int[] arr; //the nodes
private int[] size; //the levels on the graph
public QuickFindWeighted(int n) {
arr = new int[n];
size = new int[n];
for (int i=0;i<n;i++) {
arr[i] = i;
size[i] = 1;
}
}
public int root(int i) {
while (i != arr[i]) {
i = arr[i];
}
return i;
}
public boolean connected(int a, int b) {
return root(a)==root(b);
}
public void union(int a, int b){
// System.out.println("unioning " + a + " and " + b);
int i = root(a);
int j = root(b);
// System.out.println(a + "'s root is " + i + " and " + b + "'s root is " + j);
// System.out.println(a + "'s level is " + size[i] + " and " + b + "'s level is " + size[j]);
if (size[i] < size[j]) {
arr[i] = j;
size[j]+=size[i];
}
else {
arr[j] = i;
size[i]+=size[j];
}
}
public String toString(){
for (int i=0;i<arr.length;i++){
System.out.print(arr[i] + " ");
}
System.out.println("");
return ("Length of Array is: " + arr.length);
}
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment