quick sort in javascript

Here is how you can implement Quick Sort in JavaScript:

index.tsx
function quickSort(arr, left, right) {
  var len = arr.length,
    pivot,
    partitionIndex;

  if (left < right) {
    pivot = right;
    partitionIndex = partition(arr, pivot, left, right);

    quickSort(arr, left, partitionIndex - 1);
    quickSort(arr, partitionIndex + 1, right);
  }
  return arr;
}

function partition(arr, pivot, left, right) {
  var pivotValue = arr[pivot],
    partitionIndex = left;

  for (var i = left; i < right; i++) {
    if (arr[i] < pivotValue) {
      swap(arr, i, partitionIndex);
      partitionIndex++;
    }
  }
  swap(arr, right, partitionIndex);
  return partitionIndex;
}

function swap(arr, i, j) {
  var temp = arr[i];
  arr[i] = arr[j];
  arr[j] = temp;
}
703 chars
35 lines

You can call the quickSort function passing the array you want to sort as the first argument and optionally the indexes of the starting and ending elements as the second and third arguments, respectively. If not specified, the algorithm will assume that you want to sort the entire array.

index.tsx
let arr = [5, 2, 1, 8, 4, 9];

console.log(quickSort(arr)); // [1, 2, 4, 5, 8, 9]
82 chars
4 lines

gistlibby LogSnag