iterative quicksort algorithm javascript

Solutions on MaxInterview for iterative quicksort algorithm javascript by the best coders in the world

showing results for - "iterative quicksort algorithm javascript"
Janice
26 May 2017
1const swap = (arr: number[], i: number, j: number) => {
2  const tmp = arr[i]
3  const retArr = arr
4  retArr[i] = arr[j]
5  retArr[j] = tmp
6  return retArr
7};
8const partition = (arr: number[], low: number, high: number) => {
9  let q = low; let i;
10  for (i = low; i < high; i++) {
11    if (arr[i] < arr[high]) {
12      swap(arr, i, q)
13      q += 1
14    }
15  }
16  swap(arr, i, q)
17  return q
18};
19const quickSort = (arr: number[], low: number, high: number) => {
20  if (low < high) {
21    const pivot = partition(arr, low, high)
22    quickSort(arr, low, pivot - 1)
23    quickSort(arr, pivot + 1, high)
24    return arr
25  }
26  return []
27}
28quickSort([9, 8, 7, 6, 5, 4, 3, 2, 1], 4, 9) // [9, 8, 7, 6, undefined, 1, 2, 3, 4, 5]