@ickb/utils
Version:
General utilities built on top of CCC
101 lines • 2.38 kB
JavaScript
export class MinHeap {
constructor(lessFunc, heap) {
Object.defineProperty(this, "lessFunc", {
enumerable: true,
configurable: true,
writable: true,
value: lessFunc
});
Object.defineProperty(this, "heap", {
enumerable: true,
configurable: true,
writable: true,
value: heap
});
}
static from(lessFunc, unordered = []) {
const heap = new MinHeap(lessFunc, [...unordered]);
const n = heap.len();
for (let i = (n >> 1) - 1; i >= 0; i--) {
heap.down(i, n);
}
return heap;
}
less(i, j) {
return this.lessFunc(this.heap, i, j);
}
len() {
return this.heap.length;
}
isEmpty() {
return this.heap.length === 0;
}
push(x) {
this.heap.push(x);
this.up(this.len() - 1);
}
pop() {
if (this.len() === 0) {
return;
}
const n = this.len() - 1;
this.swap(0, n);
this.down(0, n);
return this.heap.pop();
}
remove(i) {
if (this.len() <= i) {
return;
}
const n = this.len() - 1;
if (n != i) {
this.swap(i, n);
if (!this.down(i, n)) {
this.up(i);
}
}
return this.pop();
}
fix(i) {
if (this.len() <= i) {
return;
}
if (!this.down(i, this.len())) {
this.up(i);
}
}
up(j) {
while (true) {
const i = (j - 1) >> 1;
if (i == j || !this.less(j, i)) {
break;
}
this.swap(i, j);
j = i;
}
}
down(i0, n) {
let i = i0;
while (true) {
const j1 = (i << 1) + 1;
if (j1 >= n || j1 < 0) {
break;
}
let j = j1;
const j2 = j1 + 1;
if (j2 < n && this.less(j2, j1)) {
j = j2;
}
if (!this.less(j, i)) {
break;
}
this.swap(i, j);
i = j;
}
return i > i0;
}
swap(i, j) {
[this.heap[i], this.heap[j]] = [this.heap[j], this.heap[i]];
}
}
//# sourceMappingURL=heap.js.map