-
Notifications
You must be signed in to change notification settings - Fork 0
/
binaryMinHeap.js
101 lines (70 loc) · 1.9 KB
/
binaryMinHeap.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
97
98
99
100
101
class BinaryMinHeap{
constructor(){
this.values = [];
}
insert(val){
this.values.push(val);
this.bubbleUp();
}
/////
extractMin(){
if(this.values.length > 0){
this.swap(0,this.values.length-1);
const extracted = this.values.pop();
this.bubbleDown();
return extracted;
}else{
this.values = [];
}
}
/////
bubbleUp(){
let index = this.values.length - 1;
while(index > 0){
let parentIndex = Math.floor((index-1)/2);
if(this.values[parentIndex] > this.values[index]){
this.swap(parentIndex, index);
index = parentIndex;
}else{
return this.values;
}
}
}
////
bubbleDown(){
let parentIdx = 0;
while(true){
const element = this.values[parentIdx];
const leftIdx = parentIdx * 2 + 1;
const rightIdx = parentIdx * 2 + 2;
const leftEl = this.values[leftIdx];
const rightEl = this.values[rightIdx];
if(leftEl < element && leftEl < rightEl && rightEl && leftEl){
this.swap(leftIdx, parentIdx);
parentIdx = leftIdx;
}else if(rightEl < element && rightEl < leftEl && rightEl && leftEl){
this.swap(rightIdx, parentIdx);
parentIdx = rightIdx;
}else{
break;
}
}
}
////
swap(idx1,idx2){
const temp = this.values[idx1];
this.values[idx1] = this.values[idx2];
this.values[idx2] = temp;
}
}
let heap = new BinaryMinHeap();
heap.insert(41);
heap.insert(39);
heap.insert(33);
heap.insert(18);
heap.insert(27);
heap.insert(12);
heap.insert(55);
heap.insert(53);
heap.extractMin();
console.log(heap.values);