-
Notifications
You must be signed in to change notification settings - Fork 0
/
binary-heap.js
96 lines (79 loc) · 1.88 KB
/
binary-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
class BinaryHeap {
constructor(){
this.heap = [null];
this.pointer = 0;
}
isEmpty(){
return this.pointer == 0;
}
insert(item){
this.heap.push(item);
this.pointer++;
this.percUp(this.pointer);
}
percUp(index){
while(Math.floor(index / 2) > 0){
let i = Math.floor(index / 2);
if(this.heap[i] > this.heap[index]){
let tmp = this.heap[i];
this.heap[i] = this.heap[index];
this.heap[index] = tmp;
}
index = i;
}
}
deleteMin(){
if(this.isEmpty()){
throw new Error('Heap is empty');
}
let v = this.heap[1];
this.heap[1] = this.heap[this.pointer];
this.heap.pop();
this.pointer--;
this.percDown(1);
return v;
}
percDown(index){
while(index * 2 <= this.pointer){
let i = this.findMinIndex(index);
if(this.heap[index] > this.heap[i]){
let tmp = this.heap[i];
this.heap[i] = this.heap[index];
this.heap[index] = tmp;
}
index = i;
}
}
findMinIndex(index){
if(index * 2 + 1 > this.pointer){
return index * 2;
}
else{
if(this.heap[index * 2] <= this.heap[index * 2 + 1]){
return index * 2;
}
else{
return index * 2 + 1;
}
}
}
getMin(){
if(this.isEmpty()){
throw new Error('Heap is empty');
}
return this.heap[1];
}
buildHeap(vals){
for(v of vals){
this.insert(v);
}
}
}
let bh = new BinaryHeap();
bh.insert(100);
bh.insert(1);
bh.insert(5);
console.log(bh.heap);
while(!bh.isEmpty()){
console.log(bh.deleteMin());
}