-
Notifications
You must be signed in to change notification settings - Fork 1k
Expand file tree
/
Copy pathheap.js
More file actions
69 lines (57 loc) · 1.77 KB
/
Copy pathheap.js
File metadata and controls
69 lines (57 loc) · 1.77 KB
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
class Heap {
constructor(compareFunc) {
this.values = [null];
this.compareFunc = compareFunc || ((x, y) => x < y);
}
get top() {
return this.values[1];
}
get count() {
return this.values.length - 1;
}
get isEmpty() {
return this.count === 0;
}
add(value) {
let index = this.values.length;
this.values.push(value);
while (index > 1 && this.compareFunc(value, this.values[index >> 1])) {
this.values[index] = this.values[index >> 1];
index >>= 1;
}
this.values[index] = value;
}
removeTop() {
const value = this.values[this.values.length - 1];
this.values.pop();
if (!this.isEmpty) {
this._heapifyDown(1, value);
}
}
_heapifyDown(index, value) {
while (index * 2 + 1 < this.values.length) {
const isFirstChildBetter =
this.compareFunc(
this.values[index * 2],
this.values[index * 2 + 1]
);
const smallerChildIndex = isFirstChildBetter ?
index * 2 :
index * 2 + 1;
if (this.compareFunc(this.values[smallerChildIndex], value)) {
this.values[index] = this.values[smallerChildIndex];
index = smallerChildIndex;
} else {
break;
}
}
if (index * 2 < this.values.length) {
const smallerChildIndex = index * 2;
if (this.compareFunc(this.values[smallerChildIndex], value)) {
this.values[index] = this.values[smallerChildIndex];
index = smallerChildIndex;
}
}
this.values[index] = value;
}
}