-
Notifications
You must be signed in to change notification settings - Fork 0
Expand file tree
/
Copy pathminHeap.js
More file actions
80 lines (65 loc) · 1.41 KB
/
minHeap.js
File metadata and controls
80 lines (65 loc) · 1.41 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
getMinHeap = () => {
const heap = [];
const getChildIndexes = (parentIndex) => ({
left: 2 * parentIndex +1,
right: 2 * parentIndex + 2
})
const getParentIndex = childIndex => Math.floor((childIndex - 1) / 2);
const bubbleUp = () => {
let i = heap.length - 1;
let value = heap[i];
while (i > 0) {
const parentIndex = getParentIndex(i);
const parent = heap[parentIndex];
if (!parent || value > parent) break;
heap[parentIndex] = value;
heap[i] = parent;
i = parentIndex;
}
}
const sinkDown = () => {
let i = 0;
const length = heap.length;
const root = heap[0];
let leftChild, rightChild;
while(true) {
const childIndexes = getChildIndexes(i);
let swap = null;
if (childIndexes.left < length) {
leftChild = heap[childIndexes.left]
if (leftChild < root) {
swap = childIndexes.left;
}
}
if (childIndexes.right < length) {
rightChild = heap[childIndexes.right];
if (
swap === null && rightChild < root
|| swap !== null && rightChild < leftChild
) {
swap = childIndexes.right;
}
}
if (!swap) break;
heap[i] = heap[swap];
heap[swap] = root;
i = swap;
}
}
return {
enqueue(value) {
heap.push(value);
bubbleUp();
return heap;
},
dequeue() {
const min = heap[0];
const last = heap.pop();
if (heap.length > 0) {
heap[0] = last;
sinkDown();
}
return min;
}
}
}