Skip to content

Commit 351ccaa

Browse files
whoisnpabranhe
authored andcommitted
added max heap algorithm
1 parent 823ea17 commit 351ccaa

File tree

1 file changed

+77
-0
lines changed

1 file changed

+77
-0
lines changed

algorithms/data-structures/maxHeap.js

Lines changed: 77 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,77 @@
1+
class BinaryHeap {
2+
constructor() {
3+
this.heap = [];
4+
}
5+
6+
insert(value) {
7+
this.heap.push(value);
8+
this.heapify();
9+
}
10+
11+
size() {
12+
return this.heap.length;
13+
}
14+
15+
empty() {
16+
return this.size() === 0;
17+
}
18+
19+
heapify() {
20+
let index = this.size() - 1;
21+
22+
while (index > 0) {
23+
const element = this.heap[index];
24+
const parentIndex = Math.floor((index - 1) / 2);
25+
const parent = this.heap[parentIndex];
26+
27+
if (parent[0] >= element[0]) break;
28+
this.heap[index] = parent;
29+
this.heap[parentIndex] = element;
30+
index = parentIndex;
31+
}
32+
}
33+
34+
extractMax() {
35+
const max = this.heap[0];
36+
const tmp = this.heap.pop();
37+
if (!this.empty()) {
38+
this.heap[0] = tmp;
39+
this.sinkDown(0);
40+
}
41+
return max;
42+
}
43+
44+
sinkDown(index) {
45+
const left = 2 * index + 1;
46+
const right = 2 * index + 2;
47+
let largest = index;
48+
const length = this.size();
49+
50+
if (left < length && this.heap[left][0] > this.heap[largest][0]) {
51+
largest = left;
52+
}
53+
if (right < length && this.heap[right][0] > this.heap[largest][0]) {
54+
largest = right;
55+
}
56+
// swap
57+
if (largest !== index) {
58+
const tmp = this.heap[largest];
59+
this.heap[largest] = this.heap[index];
60+
this.heap[index] = tmp;
61+
this.sinkDown(largest);
62+
}
63+
}
64+
}
65+
66+
const maxHeap = new BinaryHeap();
67+
maxHeap.insert([4]);
68+
maxHeap.insert([3]);
69+
maxHeap.insert([6]);
70+
maxHeap.insert([1]);
71+
maxHeap.insert([8]);
72+
maxHeap.insert([2]);
73+
74+
while (!maxHeap.empty()) {
75+
const mx = maxHeap.extractMax();
76+
console.log(mx);
77+
}

0 commit comments

Comments
 (0)
pFad - Phonifier reborn

Pfad - The Proxy pFad of © 2024 Garber Painting. All rights reserved.

Note: This service is not intended for secure transactions such as banking, social media, email, or purchasing. Use at your own risk. We assume no liability whatsoever for broken pages.


Alternative Proxies:

Alternative Proxy

pFad Proxy

pFad v3 Proxy

pFad v4 Proxy