quick sort an array javascript code example

Example 1: quick sort in javascript

function quicksort(array) {
  if (array.length <= 1) {
    return array;
  }

  var pivot = array[0];
  
  var left = []; 
  var right = [];

  for (var i = 1; i < array.length; i++) {
    array[i] < pivot ? left.push(array[i]) : right.push(array[i]);
  }

  return quicksort(left).concat(pivot, quicksort(right));
};

Example 2: iterative quicksort algorithm javascript

const swap = (arr: number[], i: number, j: number) => {
  const tmp = arr[i]
  const retArr = arr
  retArr[i] = arr[j]
  retArr[j] = tmp
  return retArr
};
const partition = (arr: number[], low: number, high: number) => {
  let q = low; let i;
  for (i = low; i < high; i++) {
    if (arr[i] < arr[high]) {
      swap(arr, i, q)
      q += 1
    }
  }
  swap(arr, i, q)
  return q
};
const quickSort = (arr: number[], low: number, high: number) => {
  if (low < high) {
    const pivot = partition(arr, low, high)
    quickSort(arr, low, pivot - 1)
    quickSort(arr, pivot + 1, high)
    return arr
  }
  return []
}
quickSort([9, 8, 7, 6, 5, 4, 3, 2, 1], 4, 9) // [9, 8, 7, 6, undefined, 1, 2, 3, 4, 5]