quick sort on js code example

Example: 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]