Simpler Binary Heaps?
xcthulhu opened this issue · 1 comments
xcthulhu commented
Here's a simpler implementation of a Binary Heap; feel free to introduce a comparator into the constructor...
function PriorityQ(elems) {
// Implements a binary heap priority queue
var q = [null];
this.push = function (h) {
var i, j;
for (i = q.length; (j = (i / 2) | 0) && q[j] > h; q[i] = q[j], i = j);
q[i] = h;
return this;
};
this.pop = function () {
var i, j, r, t;
for (r = q[1]; q.length > 1 && r == q[1]; q[i] = t) {
for (i = 1, t = q.pop(); (j = i * 2) < q.length;) {
if (j < q.length && q[j] > q[j + 1]) j++;
if (t <= q[j]) break;
q[i] = q[i = j];
}
}
return r;
};
if (Object.prototype.toString.call(elems) === '[object Array]')
elems.forEach(this.push);
}
felipernb commented
Mind sending a pull request? (And why don't you use instanceof in the end)?