Last active
November 5, 2021 11:09
-
-
Save ramsunvtech/404ca8b53e4f8f3f4da8 to your computer and use it in GitHub Desktop.
Quick Sort 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
function quickSort(arr, left, right){ | |
var len = arr.length, | |
pivot, | |
partitionIndex; | |
if(left < right){ | |
pivot = right; | |
partitionIndex = partition(arr, pivot, left, right); | |
//sort left and right | |
quickSort(arr, left, partitionIndex - 1); | |
quickSort(arr, partitionIndex + 1, right); | |
} | |
return arr; | |
} | |
function partition(arr, pivot, left, right){ | |
var pivotValue = arr[pivot], | |
partitionIndex = left; | |
for(var i = left; i < right; i++){ | |
if(arr[i] < pivotValue){ | |
swap(arr, i, partitionIndex); | |
partitionIndex++; | |
} | |
} | |
swap(arr, right, partitionIndex); | |
return partitionIndex; | |
} | |
function swap(arr, i, j){ | |
var temp = arr[i]; | |
arr[i] = arr[j]; | |
arr[j] = temp; | |
} |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment
Sort Ascending with Duplicates.