-
Notifications
You must be signed in to change notification settings - Fork 0
/
MaxHeap.js
98 lines (77 loc) · 1.72 KB
/
MaxHeap.js
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
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
// nearly complete binary tree
class MaxHeap {
constructor() {
this.array = [Infinity];
}
get empty() {
return this.array.length <= 1;
}
// Worst case: O(n log n)
insert(...numbers) {
numbers.forEach(number => this.bubbleUp(this.array.push(number) - 1));
}
// O(1)
findMax() {
return this.array[1] || null;
}
// O(log n)
extractMax() {
if (this.array.length == 2) return this.array.pop();
let max = this.array[1];
this.array[1] = this.array.pop();
this.maxHeapify(1);
return max;
}
/* aka bubbleDown
O(log n)
*/
maxHeapify(index) {
let left = this.getLeftChild(index);
let right = this.getRightChild(index);
let max = index;
// left bigger
if (this.array[max] < this.array[left]) max = left;
if (this.array[max] < this.array[right]) max = right;
// valid heap
if (max == index) return;
this.swap(index, max);
this.maxHeapify(max);
}
// Worst case: O(log n)
bubbleUp(index) {
let parent = this.getParent(index);
if (this.array[index] <= this.array[parent])
return;
this.swap(index, parent);
this.bubbleUp(parent);
}
swap(i, j) {
let temp = this.array[i];
this.array[i] = this.array[j];
this.array[j] = temp;
}
getParent(index) {
return Math.floor(index / 2);
}
getLeftChild(index) {
return index * 2;
}
getRightChild(index) {
return index * 2 + 1;
}
visualize() {
for (let i = 1; i < this.array.length; i++) {}
}
}
module.exports = MaxHeap;
// let h = new MaxHeap();
// // h.insert(20, 9, 18, 8, 6, 5, 12, 3, 2)
// h.insert(20, 2);
// console.log(h.array);
// h.insert(11);
// console.log(h.array);
// console.log(h.extractMax());
// console.log(h.extractMax());
// console.log(h.array);
// console.log(h.extractMax());
// console.log(h.array);