tweak
This commit is contained in:
parent
47af930e18
commit
e1bb10ff8a
12 changed files with 1336 additions and 526 deletions
34
graph.js
Normal file
34
graph.js
Normal file
|
|
@ -0,0 +1,34 @@
|
|||
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; }
|
||||
}
|
||||
Loading…
Add table
Add a link
Reference in a new issue