create a quick sort in javascript

Here's an implementation of the Quicksort algorithm in JavaScript, using the Hoare partition scheme:

index.tsx
function quickSort(arr, left = 0, right = arr.length - 1) {
  if (left >= right) {
    return;
  }

  const pivot = arr[left + Math.floor((right - left) / 2)];

  const index = partition(arr, left, right, pivot);

  quickSort(arr, left, index - 1);
  quickSort(arr, index, right);

  return arr;
}

function 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;
}
618 chars
35 lines

To use it, simply call quickSort with the array as the first argument:

index.tsx
const arr = [5, 2, 6, 1, 3, 9];
quickSort(arr); // [1, 2, 3, 5, 6, 9]
70 chars
3 lines

gistlibby LogSnag