-
Notifications
You must be signed in to change notification settings - Fork 2
Expand file tree
/
Copy pathheap.js
More file actions
53 lines (47 loc) · 1.11 KB
/
heap.js
File metadata and controls
53 lines (47 loc) · 1.11 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
class MaxHeap {
constructor(values) {
this.values = values;
}
parent(index) {
return Math.floor((index - 1) / 2);
}
leftChild(index) {
return index * 2 + 1;
}
rightChild(index) {
return index * 2 + 2;
}
isLeaf(index) {
return (
index >= Math.floor(this.values.length / 2) &&
index <= this.values.length - 1
);
}
swap(index1, index2) {
const temp = this.values[index1];
this.values[index1] = this.values[index2];
this.values[index2] = temp;
}
add(element) {
this.values.push(element);
this.heapifyUp(this.values.length - 1);
}
heapifyUp(index) {
let currentIndex = index;
let parentIndex = this.parent(currentIndex);
while (
currentIndex > 0 &&
this.values[currentIndex] > this.values[parentIndex]
) {
this.swap(currentIndex, parentIndex);
currentIndex = parentIndex;
parentIndex = this.parent(parentIndex);
}
console.log(this.values);
}
}
const nums = [40, 30, 15, 10, 20];
const maxHeap = new MaxHeap(nums);
maxHeap.add(60);
// console.log(maxHeap);
// console.log(createHeap(nums));