forked from TheAlgorithms/JavaScript
- Notifications
You must be signed in to change notification settings - Fork 0
Expand file tree
/
Copy pathMaxHeap.js
More file actions
Latest commit
85 lines (72 loc) · 1.74 KB
/
Copy pathMaxHeap.js
File metadata and controls
85 lines (72 loc) · 1.74 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
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
/**
* Author: Samarth Jain
* Max Heap implementation in Javascript
*/
classBinaryHeap{
constructor(){
this.heap=[]
}
insert(value){
this.heap.push(value)
this.heapify()
}
size(){
returnthis.heap.length
}
empty(){
returnthis.size()===0
}
// using iterative approach to reorder the heap after insertion
heapify(){
letindex=this.size()-1
while(index>0){
constelement=this.heap[index]
constparentIndex=Math.floor((index-1)/2)
constparent=this.heap[parentIndex]
if(parent[0]>=element[0])break
this.heap[index]=parent
this.heap[parentIndex]=element
index=parentIndex
}
}
// Extracting the maximum element from the Heap
extractMax(){
constmax=this.heap[0]
consttmp=this.heap.pop()
if(!this.empty()){
this.heap[0]=tmp
this.sinkDown(0)
}
returnmax
}
// To restore the balance of the heap after extraction.
sinkDown(index){
constleft=2*index+1
constright=2*index+2
letlargest=index
constlength=this.size()
if(left<length&&this.heap[left][0]>this.heap[largest][0]){
largest=left
}
if(right<length&&this.heap[right][0]>this.heap[largest][0]){
largest=right
}
// swap
if(largest!==index){
consttmp=this.heap[largest]
this.heap[largest]=this.heap[index]
this.heap[index]=tmp
this.sinkDown(largest)
}
}
}
// Example
// const maxHeap = new BinaryHeap()
// maxHeap.insert([4])
// maxHeap.insert([3])
// maxHeap.insert([6])
// maxHeap.insert([1])
// maxHeap.insert([8])
// maxHeap.insert([2])
// const mx = maxHeap.extractMax()
export{BinaryHeap}