-
Notifications
You must be signed in to change notification settings - Fork 1
/
heap.js
87 lines (72 loc) · 1.68 KB
/
heap.js
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
const heap = sorter => {
let elements = [];
const root = _ => elements[0];
const empty = _ => elements.length === 0;
const length = _ => elements.length;
const parentIndex = i => Math.floor((i - 1) / 2);
const rightIndex = i => 2 * i + 2;
const leftIndex = i => 2 * i + 1;
const hasIndex = i => i >= 0 && i < length();
const hasParent = i => hasIndex(parentIndex(i));
const hasRight = i => hasIndex(rightIndex(i));
const hasLeft = i => hasIndex(leftIndex(i));
const parent = i => elements[parentIndex(i)];
const left = i => elements[leftIndex(i)];
const right = i => elements[rightIndex(i)];
const higher = (a, b) => sorter(a, b) < 0;
const swap = (i, j) => {
const temp = elements[i];
elements[i] = elements[j];
elements[j] = temp;
};
const heapifyUp = start => {
let i = start;
while (hasParent(i) && higher(elements[i], parent(i))) {
swap(i, parentIndex(i));
i = parentIndex(i);
}
};
const heapifyDown = start => {
let i = start;
while (hasLeft(i)) {
if (
higher(left(i), elements[i])
|| (hasRight(i) && higher(right(i), elements[i]))
) {
if (!hasRight(i) || higher(left(i), right(i))) {
swap(i, leftIndex(i));
i = leftIndex(i);
} else {
swap(i, rightIndex(i));
i = rightIndex(i);
}
} else {
break;
}
}
};
const remove = _ => {
const root = elements[0];
if (length() === 1) {
elements = [];
} else {
elements[0] = elements.pop();
heapifyDown(0);
}
return root;
};
const insert = data => {
elements.push(data);
heapifyUp(length() - 1);
};
const getElements = _ => elements;
return {
remove,
insert,
length,
empty,
root,
getElements
};
}
module.exports = heap;