Last active
August 29, 2015 13:56
-
-
Save jack-wong-build/9071461 to your computer and use it in GitHub Desktop.
Quick sort.
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
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