Skip to content

Commit 0a82d13

Browse files
committed
add extractMax method to max_binary_heap class
1 parent 6d0d706 commit 0a82d13

File tree

1 file changed

+52
-3
lines changed

1 file changed

+52
-3
lines changed

Diff for: Binary Heaps/max_binary_heap.js

+52-3
Original file line numberDiff line numberDiff line change
@@ -5,13 +5,52 @@ class MaxBinaryHeap {
55
insert(value) {
66
this.values.push(value);
77
let curIdx = this.values.length - 1;
8-
let parentIdx = Math.floor(((curIdx) - 1) / 2);
8+
let parentIdx = Math.floor((curIdx - 1) / 2);
99
while (this.values[curIdx] > this.values[parentIdx]) {
10-
[this.values[curIdx], this.values[parentIdx]] = [this.values[parentIdx], this.values[curIdx]];
10+
[this.values[curIdx], this.values[parentIdx]] = [
11+
this.values[parentIdx],
12+
this.values[curIdx],
13+
];
1114
curIdx = parentIdx;
12-
parentIdx = Math.floor(((curIdx) - 1) / 2);
15+
parentIdx = Math.floor((curIdx - 1) / 2);
1316
}
1417
}
18+
19+
extractMax() {
20+
//remove root
21+
[this.values[0], this.values[this.values.length - 1]] = [
22+
this.values[this.values.length - 1],
23+
this.values[0],
24+
];
25+
let oldRoot = this.values.pop();
26+
let curIdx = 0;
27+
let child_leftIdx = 2 * curIdx + 1;
28+
let child_rightIdx = 2 * curIdx + 2;
29+
while (
30+
(this.values[curIdx] < this.values[child_leftIdx] ||
31+
this.values[curIdx] < this.values[child_rightIdx]) &&
32+
child_rightIdx <= this.values.length - 1 &&
33+
child_leftIdx <= this.values.length - 1
34+
) {
35+
if (this.values[child_leftIdx] > this.values[child_rightIdx]) {
36+
[this.values[curIdx], this.values[child_leftIdx]] = [
37+
this.values[child_leftIdx],
38+
this.values[curIdx],
39+
];
40+
curIdx = child_leftIdx;
41+
child_leftIdx = 2 * curIdx + 1;
42+
} else {
43+
[this.values[curIdx], this.values[child_rightIdx]] = [
44+
this.values[child_rightIdx],
45+
this.values[curIdx],
46+
];
47+
curIdx = child_rightIdx;
48+
child_rightIdx = 2 * curIdx + 2;
49+
}
50+
}
51+
52+
return oldRoot;
53+
}
1554
}
1655

1756
const heap = new MaxBinaryHeap();
@@ -22,4 +61,14 @@ heap.insert(38);
2261
heap.insert(45);
2362
console.log(heap);
2463
heap.insert(200);
64+
console.log(heap);
65+
console.log(heap.extractMax());
66+
console.log(heap);
67+
console.log(heap.extractMax());
68+
console.log(heap);
69+
console.log(heap.extractMax());
70+
console.log(heap);
71+
console.log(heap.extractMax());
72+
console.log(heap);
73+
console.log(heap.extractMax());
2574
console.log(heap);

0 commit comments

Comments
 (0)