There was an error while loading. Please reload this page.
1 parent 04503c2 commit 524f7a3Copy full SHA for 524f7a3
MaxBinaryHeap.js
@@ -0,0 +1,27 @@
1
+// [a, b, b, c, c, c, c]
2
+// left child index - (index * 2) + 1
3
+// right child index -> (index * 2) + 2
4
+// parent index -> Math.floor((index - 1) / 2) ;
5
+
6
+class MaxBinaryHeap {
7
+constructor() {
8
+this.values = [];
9
+}
10
+insert(value) {
11
+this.values.push(value);
12
13
+let currentIndex = this.values.length - 1;
14
15
+while (currentIndex > 0) {
16
+let parentIndex = Math.floor((currentIndex - 1) / 2);
17
18
+if (this.values[currentIndex] > this.values[parentIndex]) {
19
+// swap
20
+let parent = this.values[parentIndex];
21
+this.values[parentIndex] = this.values[currentIndex];
22
+this.values[currentIndex] = parent;
23
+currentIndex = parentIndex;
24
+} else break;
25
26
27
0 commit comments