-
Notifications
You must be signed in to change notification settings - Fork 0
/
maxHeapRemove.js
82 lines (64 loc) · 1.71 KB
/
maxHeapRemove.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
class maxheap{
constructor(){
this.heap=[]
}
insert(value){
this.heap.push(value)
this.shiftUp(this.heap.length-1)
}
shiftUp(index){
let currentvalue=this.heap[index]
let parentindex=Math.floor((index-1)/2)
let parentvalue=this.heap[parentindex]
if(index>0&¤tvalue>parentvalue){
this.heap[index]=parentvalue
this.heap[parentindex]=currentvalue
this.shiftUp(parentindex)
}
}
remove(){
let minValue=this.heap[0]
let lastValue=this.heap.pop()
if(this.heap.length>0){
this.heap[0]=lastValue
this.shiftDown(0)
}
return minValue
}
shiftDown(index){
let currentvalue=this.heap[index]
let leftchildIndex=index*1+1
let rightchildIndex=index*1+2
let maxChildIndex
if(rightchildIndex>=this.heap.length){
if(leftchildIndex>=this.heap.length){
return
}else{
maxChildIndex=leftchildIndex
}
}else{
if(this.heap[leftchildIndex]>=this.heap[rightchildIndex]){
maxChildIndex=leftchildIndex
}else{
maxChildIndex=rightchildIndex
}
}
let maxChildValue=this.heap[maxChildIndex]
if(maxChildValue>currentvalue){
this.heap[index]=maxChildValue
this.heap[maxChildIndex]=currentvalue
this.shiftDown(maxChildIndex)
}
}
display(){
console.log(this.heap);
}
}
let heap=new maxheap
heap.insert(20)
heap.insert(15)
heap.insert(10)
heap.insert(5)
heap.display()
heap.remove()
heap.display()