Created
January 10, 2014 19:40
-
-
Save jack-wong-build/8361178 to your computer and use it in GitHub Desktop.
Quick sort implementation in JavaScript.
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
var quickSort = function(array, left, right){ | |
var leftIndex = partition(array, left, right); | |
if (left < leftIndex - 1){ | |
quickSort(array, left, leftIndex-1); | |
} | |
if (right > leftIndex){ | |
quickSort(array, leftIndex, right); | |
} | |
return array; | |
} | |
var swap = function(array, left, right){ | |
var temp; | |
temp = array[leftIndex]; | |
array[leftIndex] = array[rightIndex]; | |
array[rightIndex] = temp; | |
} | |
var partition = function(array, left, right){ | |
var pivotIndex = Math.floor( (left + right) / 2); | |
var pivot = array[pivotIndex]; | |
leftIndex = left; | |
rightIndex = right; | |
while (leftIndex <= rightIndex){ | |
while(array[leftIndex] < pivot){ | |
leftIndex++; | |
} | |
while(array[rightIndex] > pivot){ | |
rightIndex--; | |
} | |
if (leftIndex <= rightIndex){ | |
swap(array, left, right); | |
leftIndex++; | |
rightIndex--; | |
} | |
} | |
return leftIndex; | |
} |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment
You could even do this by utilizing JavaScript array filter method.