Skip to content

Instantly share code, notes, and snippets.

@eduardolundgren
Created November 10, 2012 06:30
Show Gist options
  • Save eduardolundgren/4050182 to your computer and use it in GitHub Desktop.
Save eduardolundgren/4050182 to your computer and use it in GitHub Desktop.
DisjointSet = function(size) {
var instance = this,
parent_,
i;
size = instance.size = size || 0;
parent_ = instance.parent = new Uint32Array(size);
for (i = 0; i < size; i++) {
parent_[i] = i;
}
};
DisjointSet.prototype = {
parent: null,
size: null,
find: function(i) {
var instance = this,
parent_ = instance.parent,
result;
    if (parent_[i] === i) {
        return i;
    }
    else {
result = instance.find(parent_[i]);
parent_[i] = result;
        return result;
    }
},
union: function(i, j) {
var instance = this,
iRepresentative = instance.find(i),
jRepresentative = instance.find(j);
instance.parent[iRepresentative] = jRepresentative;
}
};
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment