Skip to content

Instantly share code, notes, and snippets.

@shuboc
Last active January 23, 2023 18:50
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/46ba75900b1e8ff1b5952ee94b33bd0c to your computer and use it in GitHub Desktop.
Save shuboc/46ba75900b1e8ff1b5952ee94b33bd0c to your computer and use it in GitHub Desktop.
JavaScript Implementation of Quick Sort (Hoare Partition Scheme)
// https://en.wikipedia.org/wiki/Quicksort#Hoare_partition_scheme
function quickSort(arr, lo, hi) {
if (lo >= 0 && hi >= 0 && lo < hi) {
const p = partition(arr, lo, hi);
quickSort(arr, lo, p);
quickSort(arr, p + 1, hi);
}
}
function partition(arr, lo, hi) {
const pivot = arr[Math.floor((lo + hi) / 2)];
let i = lo - 1;
let j = hi + 1;
while (true) {
do {
i++;
} while (arr[i] < pivot);
do {
j--;
} while (arr[j] > pivot);
if (i >= j) {
return j;
}
swap(arr, i, j);
}
}
function swap(arr, i, j) {
const tmp = arr[i];
arr[i] = arr[j];
arr[j] = tmp;
}
let arr = [9, 4, 1, 6, 7, 3, 8, 2, 5];
quickSort(arr, 0, arr.length - 1);
@zakhar-bykov
Copy link

Thanks, man. I tried to integrate your code into my and add some features... and I lost maybe two or three hours to fix the problems.

Your script is #@!)) Sorry. Try it with random generated array, and array with repeatable numbers.
Surprise — it doesnt work and goes to recursion.

Finally I used this one... https://itnext.io/a-sort-of-quick-guide-to-quicksort-and-hoares-partitioning-scheme-in-javascript-7792112c6d1

Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment