Repository navigation
Expand file tree
/
Copy pathHeap.js
More file actions
105 lines (97 loc) · 2.47 KB
/
Copy pathHeap.js
File metadata and controls
105 lines (97 loc) · 2.47 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
class Heap {
constructor() {
this.heap = [];
}
// Add an element to the heap
add(element) {
this.heap.push(element);
this.bubbleUp(this.heap.length - 1);
}
// Remove the root element of the heap and return a sorted array of the removed elements
sort() {
const sorted = [];
while (!this.isEmpty()) {
const max = this.remove();
sorted.push(max);
}
return sorted;
}
// Remove and return the largest element from the heap
remove() {
const last = this.heap.pop();
if (this.heap.length > 0) {
const max = this.heap[0];
this.heap[0] = last;
this.bubbleDown(0);
return max;
} else {
return last;
}
}
// Return true if the heap is empty, false otherwise
isEmpty() {
return this.heap.length === 0;
}
// Find the index of the first element in the heap that satisfies the given predicate function
find(predicate) {
for (let i = 0; i < this.heap.length; i++) {
if (predicate(this.heap[i])) {
return i;
}
}
return -1;
}
// Get the index of the parent of the element at the given index
getParentIndex(index) {
return Math.floor((index - 1) / 2);
}
// Bubble up an element to its correct position
bubbleUp(index) {
const element = this.heap[index];
while (index > 0) {
const parentIndex = this.getParentIndex(index);
const parent = this.heap[parentIndex];
if (element <= parent) {
break;
}
this.heap[parentIndex] = element;
this.heap[index] = parent;
index = parentIndex;
}
}
// Bubble down an element to its correct position
bubbleDown(index) {
const element = this.heap[index];
while (index < this.heap.length) {
const leftChildIndex = index * 2 + 1;
const rightChildIndex = index * 2 + 2;
let maxIndex = index;
let max = element;
if (
leftChildIndex < this.heap.length &&
this.heap[leftChildIndex] > max
) {
maxIndex = leftChildIndex;
max = this.heap[leftChildIndex];
}
if (
rightChildIndex < this.heap.length &&
this.heap[rightChildIndex] > max
) {
maxIndex = rightChildIndex;
max = this.heap[rightChildIndex];
}
if (maxIndex === index) {
break;
}
this.heap[maxIndex] = element;
this.heap[index] = max;
index = maxIndex;
}
}
// Get the size of the heap
size() {
return this.heap.length;
}
}
module.exports = Heap;