Created
July 26, 2018 18:19
-
-
Save praveenpuglia/bcb40d128ef82e21a843d7b6c4f0e013 to your computer and use it in GitHub Desktop.
Quick Sort implemented in JS
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, left = 0, right = array.length - 1) { | |
console.log("CALLED"); | |
let partitionIndex; | |
let pivotIndex; | |
if(left < right) { | |
pivotIndex = right; | |
partitionIndex = partition(array, left, right, pivotIndex); | |
quickSort(array, left, partitionIndex - 1); | |
quickSort(array, partitionIndex + 1, right); | |
} | |
return array; | |
} | |
function partition(a, left, right, pivotIndex) { | |
let partitionIndex = left, | |
pivot = array[pivotIndex]; | |
for(let i = left; i < right; i++) { | |
if(a[i] < pivot) { | |
[a[i], a[partitionIndex]] = [a[partitionIndex], a[i]]; | |
partitionIndex += 1 | |
} | |
} | |
[a[right], a[partitionIndex]] = [a[partitionIndex], a[right]]; | |
return partitionIndex; | |
} |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment