Skip to content

Commit 5338710

Browse files
committed
update: added MinHeap, support for collection in constructor
1 parent c2f5934 commit 5338710

File tree

2 files changed

+87
-3
lines changed

2 files changed

+87
-3
lines changed

src/_DataStructures_/Heaps/MaxHeap/index.js

+8-3
Original file line numberDiff line numberDiff line change
@@ -1,6 +1,11 @@
11
class MaxHeap {
2-
constructor() {
2+
constructor(collection) {
33
this.heap = [];
4+
if (collection) {
5+
collection.forEach((element) => {
6+
this.add(element);
7+
});
8+
}
49
}
510

611
add(element) {
@@ -25,13 +30,13 @@ class MaxHeap {
2530
// restore the heapify property
2631
// eslint-disable-next-line no-underscore-dangle
2732
this.__heapify(0);
28-
return max;
2933
}
3034

3135
if (this.heap.length === 1) {
3236
this.heap.pop();
33-
return max;
3437
}
38+
39+
return max;
3540
}
3641

3742
__heapify(index) {
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,79 @@
1+
class MinHeap {
2+
constructor(collection) {
3+
this.heap = [];
4+
5+
if (collection) {
6+
collection.forEach((element) => {
7+
this.add(element);
8+
});
9+
}
10+
}
11+
12+
add(element) {
13+
this.heap.push(element);
14+
// check for the parent element & swap if required
15+
// eslint-disable-next-line no-underscore-dangle
16+
this.__traverseUpAndSwap(this.heap.length - 1);
17+
}
18+
19+
getMin() {
20+
return this.heap[0] || null;
21+
}
22+
23+
remove() {
24+
const min = this.heap[0] || null;
25+
26+
if (this.heap.length > 1) {
27+
this.heap[0] = this.heap[this.heap.length - 1];
28+
this.heap.pop();
29+
// eslint-disable-next-line no-underscore-dangle
30+
this.__heapify(0);
31+
}
32+
if (this.heap.length === 1) {
33+
this.heap.pop();
34+
}
35+
return min;
36+
}
37+
38+
destroy() {
39+
this.heap = [];
40+
}
41+
42+
// eslint-disable-next-line consistent-return
43+
__traverseUpAndSwap(index) {
44+
if (index <= 0) return null;
45+
46+
const parent = Math.floor(index / 2);
47+
48+
if (this.heap[parent] > this.heap[index]) {
49+
const temp = this.heap[parent];
50+
this.heap[parent] = this.heap[index];
51+
this.heap[index] = temp;
52+
// eslint-disable-next-line no-underscore-dangle
53+
this.__traverseUpAndSwap(parent);
54+
}
55+
}
56+
57+
__heapify(index) {
58+
const left = index * 2;
59+
const right = index * 2 + 1;
60+
61+
let smallest = index;
62+
63+
if (this.heap.length > left && this.heap[smallest] > this.heap[left]) {
64+
smallest = left;
65+
}
66+
if (this.heap.length > right && this.heap[smallest] > this.heap[right]) {
67+
smallest = right;
68+
}
69+
if (smallest !== index) {
70+
const tmp = this.heap[smallest];
71+
this.heap[smallest] = this.heap[index];
72+
this.heap[index] = tmp;
73+
// eslint-disable-next-line no-underscore-dangle
74+
this.__heapify(smallest);
75+
}
76+
}
77+
}
78+
79+
module.exports = MinHeap;

0 commit comments

Comments
 (0)