Skip to content

Instantly share code, notes, and snippets.

@woonketwong woonketwong/quickSort
Last active Aug 29, 2015

Embed
What would you like to do?
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
You can’t perform that action at this time.