Skip to content

Instantly share code, notes, and snippets.

@yiboyang
Last active February 9, 2016 00:54
Show Gist options
  • Save yiboyang/a2017568422691cb9410 to your computer and use it in GitHub Desktop.
Save yiboyang/a2017568422691cb9410 to your computer and use it in GitHub Desktop.
Lightweight union find/disjoint set data structure with path compression
// Construct a UnionFind object for integer elements 0... n-1
function UnionFind(n) {
this.s = []; // Underlying array
this.numSets = n;
for (var i = 0; i < n; i++) // initial representatives are -1
this.s[i] = -1
};
// Search for element y and return the index of the root of the tree containing y;
// does path compression on each find
UnionFind.prototype.find = function (y) {
if (this.s[y] < 0)
return y;
else
return this.s[y] = this.find(this.s[y]);
};
// Form the union of sets containing values x and y using "union by size" strategy
UnionFind.prototype.union = function (x, y) {
var rootx = this.find(x);
var rooty = this.find(y);
if (rootx === rooty)
return -1;
this.numSets--;
var smallroot, bigroot;
if (this.s[rootx] <= this.s[rooty]) {
smallroot = rooty;
bigroot = rootx;
}
else {
smallroot = rootx;
bigroot = rooty;
}
this.s[bigroot] += this.s[smallroot];
return this.s[smallroot] = bigroot;
};
// Return the size of the tree containing x
UnionFind.prototype.size = function (x) {
var root = this.find(x);
return -(this.s[root]);
};
// Make all underlying sets disjoint
UnionFind.prototype.clear = function () {
for (var i = 0; i < this.s.length; i++)
this.s[i] = -1
};
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment