Repository navigation
Expand file tree
/
Copy pathMaxHeap.js
More file actions
80 lines (65 loc) · 1.52 KB
/
Copy pathMaxHeap.js
File metadata and controls
80 lines (65 loc) · 1.52 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
class MaxHeap {
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);
}
pop() {
if (this.isEmpty()) {
return null;
}
const root = this.heap[0];
const lastValue = this.heap.pop();
if (!this.isEmpty()) {
this.heap[0] = lastValue;
this.bubbleDown(0);
}
return root;
}
bubbleUp(index) {
const parentIndex = Math.floor((index - 1) / 2);
if (this.heap[parentIndex] < this.heap[index]) {
[this.heap[parentIndex], this.heap[index]] = [
this.heap[index],
this.heap[parentIndex],
];
this.bubbleUp(parentIndex);
}
}
bubbleDown(index) {
const leftChildIndex = 2 * index + 1;
const rightChildIndex = 2 * index + 2;
let maxChildIndex = index;
if (
leftChildIndex < this.heap.length &&
this.heap[leftChildIndex] > this.heap[maxChildIndex]
) {
maxChildIndex = leftChildIndex;
}
if (
rightChildIndex < this.heap.length &&
this.heap[rightChildIndex] > this.heap[maxChildIndex]
) {
maxChildIndex = rightChildIndex;
}
if (maxChildIndex !== index) {
[this.heap[index], this.heap[maxChildIndex]] = [
this.heap[maxChildIndex],
this.heap[index],
];
this.bubbleDown(maxChildIndex);
}
}
}
module.exports = MaxHeap;