@@ -176,29 +176,26 @@ export function quickSortWithArray(array) {
176
176
* @return {Array }
177
177
*
178
178
*/
179
- export function quickSort ( array , lo , hi ) {
179
+ export function quickSort ( array , lo = 0 , hi = array . length ) {
180
180
checkArray ( array ) ;
181
- lo = typeof lo === "number" ? lo : 0 ;
182
- hi = typeof hi === "number" ? hi : array . length ;
183
- if ( hi <= lo ) return array ;
181
+ if ( array . length <= 1 || hi <= lo ) return array ;
184
182
185
183
const partition = ( arr , left , right ) => {
186
- let start = left ;
187
- let end = right ;
184
+ let i = left ;
185
+ let j = right ;
188
186
const pivot = arr [ left ] ;
189
187
190
- while ( start < end ) {
191
- while ( arr [ ++ start ] <= pivot ) if ( start === right ) break ; // eslint-disable-line no-plusplus
192
- while ( arr [ -- end ] >= pivot ) if ( end === left ) break ; // eslint-disable-line no-plusplus
193
- if ( start >= end ) break ;
194
- swap ( arr , start , end ) ;
188
+ while ( i < j ) {
189
+ while ( arr [ ++ i ] <= pivot ) if ( i === right ) break ; // eslint-disable-line no-plusplus
190
+ while ( arr [ -- j ] >= pivot ) if ( j === left ) break ; // eslint-disable-line no-plusplus
191
+ if ( i < j ) swap ( arr , i , j ) ;
195
192
}
196
- swap ( arr , left , end ) ;
197
- return end ;
193
+ swap ( arr , left , j ) ;
194
+ return j ;
198
195
} ;
199
- const pivot = partition ( array , lo , hi ) ;
200
- quickSort ( array , lo , pivot ) ;
201
- quickSort ( array , pivot + 1 , hi ) ;
196
+ const pivotIndex = partition ( array , lo , hi ) ;
197
+ quickSort ( array , lo , pivotIndex ) ;
198
+ quickSort ( array , pivotIndex + 1 , hi ) ;
202
199
203
200
return array ;
204
201
}
0 commit comments