1
+ import Comparator from '../../utils/comparator/Comparator' ;
2
+
1
3
export default class MinHeap {
2
4
constructor ( ) {
3
5
// Array representation of the heap.
4
6
this . heapContainer = [ ] ;
7
+ this . compare = new Comparator ( ) ;
5
8
}
6
9
7
10
static getLeftChildIndex ( parentIndex ) {
@@ -85,7 +88,7 @@ export default class MinHeap {
85
88
86
89
while (
87
90
MinHeap . hasParent ( currentIndex ) &&
88
- this . lessThen ( this . heapContainer [ currentIndex ] , this . parent ( currentIndex ) )
91
+ this . compare . lessThen ( this . heapContainer [ currentIndex ] , this . parent ( currentIndex ) )
89
92
) {
90
93
this . swap ( currentIndex , MinHeap . getParentIndex ( currentIndex ) ) ;
91
94
currentIndex = MinHeap . getParentIndex ( currentIndex ) ;
@@ -101,14 +104,14 @@ export default class MinHeap {
101
104
while ( this . hasLeftChild ( currentIndex ) ) {
102
105
if (
103
106
this . hasRightChild ( currentIndex ) &&
104
- this . lessThen ( this . rightChild ( currentIndex ) , this . leftChild ( currentIndex ) )
107
+ this . compare . lessThen ( this . rightChild ( currentIndex ) , this . leftChild ( currentIndex ) )
105
108
) {
106
109
nextIndex = MinHeap . getRightChildIndex ( currentIndex ) ;
107
110
} else {
108
111
nextIndex = MinHeap . getLeftChildIndex ( currentIndex ) ;
109
112
}
110
113
111
- if ( this . lessThen ( this . heapContainer [ currentIndex ] , this . heapContainer [ nextIndex ] ) ) {
114
+ if ( this . compare . lessThen ( this . heapContainer [ currentIndex ] , this . heapContainer [ nextIndex ] ) ) {
112
115
break ;
113
116
}
114
117
@@ -120,18 +123,4 @@ export default class MinHeap {
120
123
toString ( ) {
121
124
return this . heapContainer . toString ( ) ;
122
125
}
123
-
124
- compare ( a , b ) {
125
- if ( a === b ) {
126
- return 0 ;
127
- }
128
-
129
- // Min heap may be converted to max heap by simply changing this line to:
130
- // a > b ? -1 : 1
131
- return a < b ? - 1 : 1 ;
132
- }
133
-
134
- lessThen ( a , b ) {
135
- return this . compare ( a , b ) === - 1 ;
136
- }
137
126
}
0 commit comments