-
Notifications
You must be signed in to change notification settings - Fork 0
/
minHeapRemove.js
82 lines (67 loc) · 1.76 KB
/
minHeapRemove.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
class minheap{
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 minChildIndex
if(rightchildIndex>=this.heap.length){
if(leftchildIndex>=this.heap.length){
return
}else{
minChildIndex=leftchildIndex
}
}else{
if(this.heap[leftchildIndex]<=this.heap[rightchildIndex]){
minChildIndex=leftchildIndex
}else{
minChildIndex=rightchildIndex
}
}
let minChildValue=this.heap[minChildIndex]
if(minChildValue<currentvalue){
this.heap[index]=minChildValue
this.heap[minChildIndex]=currentvalue
this.shiftDown(minChildIndex)
}
}
display(){
console.log(this.heap);
}
}
let heap=new minheap
heap.insert(10)
heap.insert(15)
heap.insert(20)
heap.insert(16)
heap.insert(18)
heap.insert(22)
heap.insert(24)
heap.display()
heap.remove()
heap.display()