Union Find

(Not necessary) First, construct a bijection (a mapping) between your objects and the integers in the range [0,n) Map(objext->Integer[0,n)] Array[object 1, object 2, object 3,..., object n]

Use array to save space

int[] array = new int[len]; // assign a initial size

public void makeSet(int i) {
    array[i] = i;
}

public void union(int a, int b) {
    if(findSet(a)!=findSet(b)) {
        array[array[a]] = array[b]; 
    }
}

public int findSet(int a) {
    if(array[a]!=a) {
        array[a] = findSet(array[a]);
    }
    return array[a];
}

Self contained into a class

Use rank to balance the set

Last updated