Heap = {
function left(i) {
return 2 * i + 1;
}
function right(i) {
return 2 * i + 2;
}
function parent(i) {
return ~~((i - 1) / 2);
}
function lessThan(a, b) {
return Array.isArray(a) ? a[0] < b[0] : a < b;
}
class Heap extends Array {
constructor(...args) {
super(...args);
for (let i = ~~(this.length / 2); i >= 0; i--) this.heapify(i);
}
heapify(i) {
let [l, r, max] = [left(i), right(i), i];
if (
l < this.length &&
lessThan(this[max], this[l])
)
max = l;
if (
r < this.length &&
lessThan(this[max], this[r])
)
max = r;
if (max != i) {
[this[i], this[max]] = [this[max], this[i]];
this.heapify(max);
return max;
}
return false;
}
bubbleup(i) {
if (i == 0) return;
let p = parent(i);
if (this.heapify(p)) this.bubbleup(p);
}
sinkdown(i) {
if (i >= this.length) return;
let j = this.heapify(i);
if (j) this.sinkdown(j);
}
insert(x) {
this.push(x);
this.bubbleup(this.length - 1);
}
top() {
if (this.length == 0) throw "Empty Heap";
return this[0];
}
delTop() {
if (this.length == 0) throw "Empty Heap";
let x = this.pop();
if (this.length == 0) return;
this[0] = x;
this.sinkdown(0);
}
}
return Heap;
}