Skip to content

Instantly share code, notes, and snippets.

@jack-wong-build
Last active August 29, 2015 13:56
Show Gist options
  • Save jack-wong-build/9071461 to your computer and use it in GitHub Desktop.
Save jack-wong-build/9071461 to your computer and use it in GitHub Desktop.
Quick sort.
function quickSort(array, start, end){
var leftIndex = partition(array, start, end);
if (start < leftIndex-1){
quickSort(array, start, leftIndex-1);
}
if (start > leftIndex){
quickSort(array, leftIndex, end);
}
return array;
}
function partition(array, start, end){
var mid = Math.floor( (start + end) / 2 );
var pivot = array[mid];
var left = start;
var right = end;
while (left <= right){
while(array[left] < pivot){
left++;
}
while(array[right] > pivot){
right--;
}
if (left <= right){
swap(array, left, right);
left++;
right--;
}
}
return left;
}
function swap(array, left, right){
var temp = array[left];
array[left] = array[right];
array[right] = temp;
}
console.log(quickSort([5, 3, 4, 1, 2, 6], 0, 4));
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment