forked from mmcknett/heaps-js
-
Notifications
You must be signed in to change notification settings - Fork 2
Expand file tree
/
Copy pathminheap.js
More file actions
103 lines (90 loc) · 2.54 KB
/
minheap.js
File metadata and controls
103 lines (90 loc) · 2.54 KB
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
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
class HeapNode {
constructor(key, value) {
this.key = key;
this.value = value;
}
}
class MinHeap {
constructor() {
this.store = [];
}
// This method adds a HeapNode instance to the heap
// Time Complexity: O(log n), where n is the number of nodes in the heap
// Space Complexity: O(1)
add(key, value = key) {
const newNode = new HeapNode(key, value);
this.store.push(newNode);
this.heapUp(this.store.length - 1);
return this.store;
}
// This method removes and returns an element from the heap
// maintaining the heap structure
// Time Complexity: O(log n), where n is the number of nodes in the heap
// Space Complexity: O(1)
remove() {
if (this.store.length === 0) {
return undefined;
}
this.swap(0, this.store.length - 1);
const removed = this.store.pop();
this.heapDown(0);
return removed.value;
}
// Used for Testing
toString() {
if (!this.store.length) {
return "[]";
}
const values = this.store.map(item => item.value);
const output = `[${values.join(', ')}]`;
return output;
}
// This method returns true if the heap is empty
// Time complexity: O(1)
// Space complexity: O(1)
isEmpty() {
return this.store[0];
}
// This helper method takes an index and
// moves it up the heap, if it is less than it's parent node.
// It could be **very** helpful for the add method.
// Time complexity: O(log n), where n is the number of nodes in the heap
// Space complexity: O(1)
heapUp(index) {
const parentNodeIndex = Math.floor((index - 1) / 2);
if (index === 0 || (this.store[index].key >= this.store[parentNodeIndex].key)) {
return;
}
this.swap(index, parentNodeIndex);
this.heapUp(parentNodeIndex);
}
// This helper method takes an index and
// moves it down the heap if it's larger
// than its children
heapDown(index) {
const leftChild = index * 2 + 1;
const rightChild = index * 2 + 2;
let smaller;
if (rightChild >= this.store.length) {
if (leftChild >= this.store.length) {
return;
}
smaller = leftChild;
} else {
smaller = this.store[leftChild].key <= this.store[rightChild].key ? leftChild : rightChild;
}
if (this.store[index].key <= this.store[smaller].key) {
return;
}
this.swap(index, smaller);
this.heapDown(smaller);
}
// If you want a swap method... you're welcome
swap(index1, index2) {
const s = this.store;
[s[index1], s[index2]] = [s[index2], s[index1]];
}
}
module.exports = {
MinHeap
};