Skip to content

Instantly share code, notes, and snippets.

@shuboc
Last active April 24, 2022 16:21
Show Gist options
  • Star 0 You must be signed in to star a gist
  • Fork 0 You must be signed in to fork a gist
  • Save shuboc/5014cb7d4c415a3f940b07bdd7606ee5 to your computer and use it in GitHub Desktop.
Save shuboc/5014cb7d4c415a3f940b07bdd7606ee5 to your computer and use it in GitHub Desktop.
JavaScript Implementation of Quick Sort (Lomuto Partition Scheme)
// https://en.wikipedia.org/wiki/Quicksort#Lomuto_partition_scheme
function quickSort(arr, lo, hi) {
if (lo >= hi || lo < 0) return;
const p = partition(arr, lo, hi);
quickSort(arr, lo, p - 1);
quickSort(arr, p + 1, hi);
}
function partition(arr, lo, hi) {
const pivot = arr[hi];
let i = lo;
for (let j = lo; j < hi; ++j) {
if (arr[j] <= pivot) {
swap(arr, i, j);
i++;
}
}
swap(arr, i, hi);
return i;
}
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