xamples
epeat
ode
pproach
ptimize
est
Use the quicksort algorithm to sort an array of integers.
'use strict'
function quickSort(arr){
(function qS(leftPointer, rightPointer, pivotIndex){
for(let i = rightPointer; i > leftPointer; i--){
if(arr[i]<arr[pivotIndex] && i>pivotIndex || arr[i]>arr[pivotIndex] && i<pivotIndex){
let tmp = arr[pivotIndex];
arr[pivotIndex] = arr[i];
arr[i] = tmp;
pivotIndex = i;
}
}
//note, using a random pivot point to prevent worst-case behavior
if(pivotIndex > leftPointer){
let ranPiv = Math.floor(Math.random()*(pivotIndex - leftPointer));
qS(0, pivotIndex, ranPiv);
}
if(pivotIndex < rightPointer){
let ranPiv = Math.floor(Math.random()*(rightPointer - pivotIndex))+pivotIndex+1;
qS(pivotIndex+1, rightPointer, ranPiv);
}
})(0, arr.length - 1, Math.floor(Math.random()*arr.length));
return arr;
}
var arr = [5,2,4,1,3,7,9,8];
quickSort(arr); //returns [1,2,3,4,5,6,7,8,9]