Skip to content

Instantly share code, notes, and snippets.

@Dornhoth
Last active July 2, 2020 19:49
Show Gist options
  • Select an option

  • Save Dornhoth/a0dcc3c4f4e4a0c21f8ccb32c4c05bab to your computer and use it in GitHub Desktop.

Select an option

Save Dornhoth/a0dcc3c4f4e4a0c21f8ccb32c4c05bab to your computer and use it in GitHub Desktop.
function quickSort(array, low, high) {
if (low < high) {
const p = partition(array, low, high);
quickSort(array, low, p);
quickSort(array, p + 1, high);
}
}
function partition(array, low, high) {
const middleIndex = Math.floor((high + low) / 2);
const pivot = array[middleIndex];
let i = low;
let j = high;
while (true) {
while (array[i] < pivot) {
i += 1;
}
while (array[j] > pivot) {
j -= 1;
}
if (j <= i) {
return j;
}
// we found a i for which array[i] is greater than the pivot
// and a j for which array[j] is smaller than the pivot so we swap them
const temp = array[i];
array[i] = array[j];
array[j] = temp;
}
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment