Repository navigation
Expand file tree
/
Copy pathMinHeap.js
More file actions
82 lines (73 loc) · 1.64 KB
/
Copy pathMinHeap.js
File metadata and controls
82 lines (73 loc) · 1.64 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
70
71
72
73
74
75
76
77
78
79
80
81
82
class MinHeap {
constructor() {
this.heap = [];
}
size() {
return this.heap.length;
}
isEmpty() {
return this.heap.length === 0;
}
peek() {
return this.isEmpty() ? null : this.heap[0];
}
add(value) {
this.heap.push(value);
this.bubbleUp(this.heap.length - 1);
}
remove() {
if (this.isEmpty()) {
return -1;
}
const smallest = this.heap[0];
const last = this.heap.pop();
if (!this.isEmpty()) {
this.heap[0] = last;
this.bubbleDown(0);
}
return smallest;
}
bubbleUp(index) {
const parentIndex = Math.floor((index - 1) / 2);
if (index > 0 && this.heap[index] < this.heap[parentIndex]) {
[this.heap[parentIndex], this.heap[index]] = [
this.heap[index],
this.heap[parentIndex],
];
this.bubbleUp(parentIndex);
}
}
bubbleDown(index) {
const leftIndex = 2 * index + 1;
const rightIndex = 2 * index + 2;
let smallestIndex = index;
if (
leftIndex < this.heap.length &&
this.heap[leftIndex] < this.heap[smallestIndex]
) {
smallestIndex = leftIndex;
}
if (
rightIndex < this.heap.length &&
this.heap[rightIndex] < this.heap[smallestIndex]
) {
smallestIndex = rightIndex;
}
if (smallestIndex !== index) {
[this.heap[index], this.heap[smallestIndex]] = [
this.heap[smallestIndex],
this.heap[index],
];
this.bubbleDown(smallestIndex);
}
}
find(predicate) {
for (let i = 0; i < this.heap.length; i++) {
if (predicate(this.heap[i])) {
return i;
}
}
return -1;
}
}
module.exports = MinHeap;