-
Notifications
You must be signed in to change notification settings - Fork 0
/
heap.js
99 lines (84 loc) · 2.11 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
88
89
90
91
92
93
94
95
96
97
98
99
class MinHeap {
constructor() {
this.items = [];
this.size = 0;
}
peek() {
if (this.size == 0) {
throw new Error('Heap is empty')
} else {
return this.items[0];
}
}
poll() {
if (this.size == 0) {
throw new Error('Heap is empty')
} else {
let result = this.items[0];
let end = this.items.pop();
this.items[0] = end;
this.size--;
this.heapifyDown();
return result;
}
}
add(item) {
this.items.push(item);
this.size++;
this.heapifyUp();
}
heapifyUp() {
let index = this.size - 1;
while (this.hasParent(index) && this.getParent(index)[1] > this.items[index][1]) {
this.swap(this.getParentIndex(index), index);
index = this.getParentIndex(index);
}
}
heapifyDown() {
let index = 0;
while (this.hasLeftChild(index)) {
let smallerChildIndex = this.getLeftChildIndex(index);
if (this.hasRightChild(index) && this.getRightChild(index)[1] < this.getLeftChild(index)[1]) {
smallerChildIndex = this.getRightChildIndex(index);
}
if (this.items[index][1] < this.items[smallerChildIndex][1]) {
break;
} else {
this.swap(index, smallerChildIndex);
}
index = smallerChildIndex;
}
}
getLeftChildIndex(parentIndex) {
return floor((2 * parentIndex) + 1);
}
getRightChildIndex(parentIndex) {
return floor((2 * parentIndex) + 2);
}
getParentIndex(childIndex) {
return floor((childIndex - 1) / 2);
}
hasLeftChild(index) {
return this.getLeftChildIndex(index) < this.size;
}
hasRightChild(index) {
return this.getRightChildIndex(index) < this.size;
}
hasParent(index) {
return this.getParentIndex(index) >= 0;
}
getLeftChild(index) {
return this.items[this.getLeftChildIndex(index)];
}
getRightChild(index) {
return this.items[this.getRightChildIndex(index)];
}
getParent(index) {
return this.items[this.getParentIndex(index)];
}
swap(index_a, index_b) {
let temp = this.items[index_a];
this.items[index_a] = this.items[index_b];
this.items[index_b] = temp;
}
}