- Notifications
You must be signed in to change notification settings - Fork 0
Expand file tree
/
Copy pathtest.js
More file actions
Latest commit
55 lines (54 loc) · 1.27 KB
/
Copy pathtest.js
File metadata and controls
55 lines (54 loc) · 1.27 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
classMinHeap{
constructor(){
this.heap=[null];
}
push(element){
this.heap.push(element);
letcurIdx=this.heap.length-1;
while(curIdx>1){
if(this.heap[curIdx]<this.heap[Math.floor(curIdx/2)]){
[this.heap[curIdx],this.heap[Math.floor(curIdx/2)]]=[
this.heap[Math.floor(curIdx/2)],
this.heap[curIdx],
];
curIdx=Math.floor(curIdx/2);
}else{
break;
}
}
return;
}
pop(){
letremoveItem=this.heap[1];
this.heap[1]=this.heap[this.heap.length-1];
this.heap.pop();
letcurIdx=1;
while(curIdx<this.heap.length){
letminIdx=curIdx;
letleftIdx=curIdx*2;
letrightIdx=curIdx*2+1;
if(
leftIdx<this.heap.length&&
this.heap[leftIdx]<this.heap[minIdx]
){
minIdx=leftIdx;
}
if(
rightIdx<this.heap.length&&
this.heap[rightIdx]<this.heap[minIdx]
){
minIdx=rightIdx;
}
if(minIdx!==curIdx){
[this.heap[curIdx],this.heap[minIdx]]=[
this.heap[minIdx],
this.heap[curIdx],
];
curIdx=minIdx;
}else{
break;
}
}
returnremoveItem;
}
}