Created
September 8, 2017 13:41
-
-
Save juanigallo/a891921a13d784ef4bdb3d4b623f3d50 to your computer and use it in GitHub Desktop.
QuickSort 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