Repository navigation
Expand file tree
/
Copy pathminHeap.js
More file actions
109 lines (98 loc) · 2.37 KB
/
Copy pathminHeap.js
File metadata and controls
109 lines (98 loc) · 2.37 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
104
105
106
107
108
109
/** Min heap class */
class MinHeap {
constructor() {
this.heap = [];
}
/**
* Get the index of the parent node of the element at i-th index.
* @param {number} i
* @returns number
*/
parent(i) {
return Math.floor((i - 1) / 2);
}
/**
* Get the index of the left child node of the element at i-th index.
* @param {number} i
* @returns number
*/
left(i) {
return 2 * i + 1;
}
/**
* Get the index of the right child node of the element at i-th index.
* @param {number} i
* @returns number
*/
right(i) {
return 2 * i + 2;
}
/**
* Get the min value from the heap, i.e. the root node.
* @returns number
*/
getMin() {
return this.heap[0];
}
/**
* Extract/remove the min value from the heap.
* @returns number
*/
extractMin() {
if (this.heap.length <= 1) {
return this.heap.shift();
}
const min = this.heap[0];
const last = this.heap.pop();
this.heap[0] = last;
this.heaptify(0);
return min;
}
/**
* Insert an element into the heap.
* @param {number} num
*/
insert(num) {
this.heap.push(num);
let currentIndex = this.heap.length - 1;
while (currentIndex > 0) {
const parentIndex = this.parent(currentIndex);
if (this.heap[parentIndex] > this.heap[currentIndex]) {
[this.heap[parentIndex], this.heap[currentIndex]] = [
this.heap[currentIndex],
this.heap[parentIndex],
];
currentIndex = parentIndex;
} else {
break;
}
[this.heap[parentIndex], this.heap[currentIndex]] = [
this.heap[currentIndex],
this.heap[parentIndex],
];
currentIndex = parentIndex;
}
}
/**
* Heapify a subtree with the root at given index.
* This method assumes that the subtrees are already heapified.
* @param {number} i
*/
heaptify(i) {
const l = this.left(i); // The index of left child
const r = this.right(i); // The index of right child
let smallest = i;
if (l < this.heap.length && this.heap[l] < this.heap[smallest]) {
smallest = l;
}
if (r < this.heap.length && this.heap[r] < this.heap[smallest]) {
smallest = r;
}
if (smallest === i) {
return;
}
[this.heap[i], this.heap[smallest]] = [this.heap[smallest], this.heap[i]];
this.heaptify(smallest);
}
}
module.exports = { MinHeap };