-
Notifications
You must be signed in to change notification settings - Fork 0
/
Copy pathheap.js
77 lines (77 loc) · 1.79 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
"use strict";
class Heap {
constructor(isLess, arr = []) {
this.arr = arr;
this.isLess = isLess;
this.size = this.arr.lenght ?? 0;
}
peek() {
return this.arr[0];
}
poll() {
const least = this.arr[0];
[this.arr[0], this.arr[this.size - 1]] = [
this.arr[this.size - 1],
this.arr[0],
];
this.arr.pop();
this.size--;
this.heapifyDown();
return least;
}
insert(el) {
this.arr.push(el);
this.size++;
this.heapifyUp();
}
hasParent(index) {
if (index <= 0) return false;
else return true;
}
hasLeftChild(index) {
if (2 * index + 1 < this.size) return true;
else return false;
}
hasRightChild(index) {
if (2 * index + 2 < this.size) return true;
else return false;
}
heapifyUp() {
let current = this.size - 1;
let parent = Math.floor((current - 1) / 2);
while (
this.hasParent(current) &&
!this.isLess(this.arr[parent], this.arr[current])
) {
[this.arr[parent], this.arr[current]] = [
this.arr[current],
this.arr[parent],
];
current = parent;
parent = Math.floor((current - 1) / 2);
}
}
heapifyDown() {
let current = 0;
let child = [2 * current + 1, 2 * current + 2];
while (this.hasLeftChild(current)) {
let smallerChild = child[0];
if (
this.hasRightChild(current) &&
this.isLess(this.arr[child[1]], this.arr[child[0]])
)
smallerChild = child[1];
if (this.arr[current] < this.arr[smallerChild]) break;
else
[this.arr[current], this.arr[smallerChild]] = [
this.arr[smallerChild],
this.arr[current],
];
current = smallerChild;
child = [2 * current + 1, 2 * current + 2];
}
}
has(el) {
return this.arr.includes(el);
}
}