-
Notifications
You must be signed in to change notification settings - Fork 0
/
Copy pathmaxBinaryHeap.js
81 lines (70 loc) · 1.85 KB
/
maxBinaryHeap.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
class MaxBinaryHeap {
constructor() {
this.values = [];
}
insert(element) {
this.values.push(element);
this.bubbleUp();
return this.values;
}
bubbleUp() {
let elementIndex = this.values.length - 1;
const element = this.values[elementIndex];
while (elementIndex > 0) {
let parentIndex = Math.floor((elementIndex - 1) / 2);
let parent = this.values[parentIndex];
if (parent > element) break;
this.values[parentIndex] = element;
this.values[elementIndex] = parent;
elementIndex = parentIndex;
}
}
extractMax() {
const max = this.values[0];
const end = this.values.pop();
if (this.values.length > 0) {
this.values[0] = end;
this.trickleDown();
}
return max;
}
trickleDown() {
const element = this.values[0];
let index = 0;
const length = this.values.length;
while (true) {
let leftChildIndex = index * 2 + 1;
let rightChildIndex = leftChildIndex + 1;
let swapIndex = null;
let leftChild, rightChild;
if (leftChildIndex < length) {
leftChild = this.values[leftChildIndex];
if (leftChild > element) swapIndex = leftChildIndex;
}
if (rightChildIndex < length) {
rightChild = this.values[rightChildIndex];
if (
(swapIndex && rightChild > leftChild) ||
(!swapIndex && rightChild > element)
)
swapIndex = rightChildIndex;
}
if (swapIndex === null) break;
this.values[index] = this.values[swapIndex];
this.values[swapIndex] = element;
index = swapIndex;
}
}
}
const maxHeap = new MaxBinaryHeap();
maxHeap.insert(1);
maxHeap.insert(3);
maxHeap.insert(10);
maxHeap.insert(5);
maxHeap.insert(2);
maxHeap.extractMax();
maxHeap.extractMax();
console.log(maxHeap.values);
// 10
// 5 3
// 1 2