Skip to content

Instantly share code, notes, and snippets.

Embed
What would you like to do?
JavaScript Implementation of Quick Sort
// https://en.wikipedia.org/wiki/Quicksort
function quickSort(arr, left, right) {
if (left < right) {
const pivotIdx = partition(arr, left, right);
quickSort(arr, left, pivotIdx - 1);
quickSort(arr, pivotIdx + 1, right);
}
}
function partition(arr, start, end) {
const pivot = arr[end];
let nextLeftIdx = start;
for (let i = start; i < end; ++i) {
if (arr[i] < pivot) {
swap(arr, nextLeftIdx, i);
nextLeftIdx++;
}
}
swap(arr, nextLeftIdx, end);
return nextLeftIdx;
}
function swap(arr, i, j) {
const tmp = arr[i];
arr[i] = arr[j];
arr[j] = tmp;
}
const arr = [9, 4, 1, 6, 7, 3, 8, 2, 5];
quickSort(arr, 0, arr.length - 1);
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment
You can’t perform that action at this time.