34 lines
971 B
JavaScript
34 lines
971 B
JavaScript
export class MinHeap {
|
|
constructor() { this.items = []; }
|
|
push(item) {
|
|
this.items.push(item);
|
|
let i = this.items.length - 1;
|
|
while (i > 0) {
|
|
const parent = (i - 1) >> 1;
|
|
if (this.items[parent].f <= item.f) break;
|
|
this.items[i] = this.items[parent];
|
|
i = parent;
|
|
}
|
|
this.items[i] = item;
|
|
}
|
|
pop() {
|
|
if (this.items.length === 0) return null;
|
|
const root = this.items[0];
|
|
const last = this.items.pop();
|
|
if (this.items.length > 0) {
|
|
let i = 0;
|
|
while (true) {
|
|
const left = i * 2 + 1;
|
|
const right = left + 1;
|
|
if (left >= this.items.length) break;
|
|
const child = right < this.items.length && this.items[right].f < this.items[left].f ? right : left;
|
|
if (this.items[child].f >= last.f) break;
|
|
this.items[i] = this.items[child];
|
|
i = child;
|
|
}
|
|
this.items[i] = last;
|
|
}
|
|
return root;
|
|
}
|
|
get length() { return this.items.length; }
|
|
}
|