Skip to content

Instantly share code, notes, and snippets.

@tjeastmond
Created May 23, 2019 06:00
Show Gist options
  • Save tjeastmond/11a6956b1717ea656815174d3bc51e09 to your computer and use it in GitHub Desktop.
Save tjeastmond/11a6956b1717ea656815174d3bc51e09 to your computer and use it in GitHub Desktop.
// quicksort
const quicksort = (arr, left = 0, right = arr.length - 1) => {
if (left >= right) return;
const pivot = arr[Math.floor((left + right) / 2)];
const index = partition(arr, left, right, pivot);
quicksort(arr, left, index - 1);
quicksort(arr, index, right);
return arr;
};
const partition = (arr, left, right, pivot) => {
while (left <= right) {
while (arr[left] < pivot) left++;
while (arr[right] > pivot) right--;
if (left <= right) {
[arr[left], arr[right]] = [arr[right], arr[left]];
left++;
right--;
}
}
return left;
};
const array1 = [1, 8, 12, 2, 4, 5, 7, 10, 6, 3, 9, 1];
const array2 = [10, -1, 2, 5, 0, 6, 4, -5];
quicksort(array1);
// quicksort(array2);
console.log("array1: ", array1);
// console.log("array2: ", array2);
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment