minheap
Version:
Simple implementation of min-heap
124 lines (111 loc) • 2.83 kB
JavaScript
// Generated by CoffeeScript 1.10.0
(function() {
var Heap, MIN_LEN;
MIN_LEN = 1 << 5;
Heap = (function() {
function Heap(compare) {
this.compare = compare;
if (this.compare == null) {
this.compare = function(a, b) {
if (a < b) {
return -1;
} else if (a > b) {
return 1;
} else {
return 0;
}
};
}
this.array = [null];
this.len = 0;
}
Heap.prototype.top = function() {
return this.array[1];
};
Heap.prototype.pop = function() {
var res;
res = this.array[1];
if (this.len === 0) {
return res;
}
this.array[1] = this.array[this.len];
this.array[this.len] = null;
this.len--;
if (this.len > 0) {
if (this.array.length > MIN_LEN && this.array.length >= this.len * 2) {
this.array.splice(this.len + 1);
}
this._traceDown(1);
}
return res;
};
Heap.prototype.push = function(val) {
if (this.len < this.array.length - 1) {
this.array[++this.len] = val;
} else {
this.array.push(val);
this.len++;
}
return this._traceUp(this.len);
};
Heap.prototype._swap = function(a, b) {
var t;
t = this.array[a];
this.array[a] = this.array[b];
this.array[b] = t;
};
Heap.prototype._traceUp = function(pos) {
var com, parent;
while (pos > 1) {
parent = Math.floor(pos / 2);
com = this.compare(this.array[pos], this.array[parent]);
if (com < 0) {
this._swap(pos, parent);
pos = parent;
} else {
break;
}
}
};
Heap.prototype._traceDown = function(pos) {
var child, com, left, right;
while (true) {
child = 0;
left = pos * 2;
if (left > this.len) {
return;
}
com = this.compare(this.array[left], this.array[pos]);
if (com < 0) {
child = left;
}
right = left + 1;
if (right <= this.len) {
if (child > 0) {
com = this.compare(this.array[right], this.array[left]);
if (com < 0) {
child = right;
}
} else {
com = this.compare(this.array[right], this.array[pos]);
if (com < 0) {
child = right;
}
}
}
if (child > 0) {
this._swap(child, pos);
pos = child;
} else {
break;
}
}
};
return Heap;
})();
if ((typeof GLOBAL !== "undefined" && GLOBAL !== null) && (typeof window === "undefined" || window === null)) {
module.exports = Heap;
} else {
window.Heap = Heap;
}
}).call(this);