DEV Community

Bukunmi Odugbesan
Bukunmi Odugbesan

Posted on

Coding Challenge Practice - Question 96

The task is to implement quicksort.

The boilerplate code

function quickSort(arr) {
  // your code here
}
Enter fullscreen mode Exit fullscreen mode

If the array is empty or has one element, it is already sorted.

if (arr.length <= 1) return arr;
Enter fullscreen mode Exit fullscreen mode

The last element is chosen as the pivot

const pivot = arr[high];
let i = low;
Enter fullscreen mode Exit fullscreen mode

i tracks where the next smaller element should go. Loop through the array, and any value smaller than the pivot is swapped to the front.

for (let j = low; j < high; j++) {
  if (arr[j] < pivot) {
    [arr[i], arr[j]] = [arr[j], arr[i]];
    i++;
  }
}
Enter fullscreen mode Exit fullscreen mode

The pivot is left in a sorted position. Everything smaller is to the left, everything bigger is to the right

[arr[i], arr[high]] = [arr[high], arr[i]];
return i;
Enter fullscreen mode Exit fullscreen mode

Split the array into two smaller parts

const pivotIndex = partition(low, high);
Enter fullscreen mode Exit fullscreen mode

Recursively sort the left and right sides of the pivot

sort(low, pivotIndex - 1);
sort(pivotIndex + 1, high);
Enter fullscreen mode Exit fullscreen mode

Each recursive call works on a smaller range, so recursion always progresses towards termination.

The final code

function quickSort(arr) {
  // your code here
  if(arr.length <= 1) return arr;

  function partition(low, high) {
    const pivot = arr[high];
    let i = low;

    for(let j = low; j < high; j++) {
      if(arr[j] < pivot) {
        [arr[i], arr[j]] = [arr[j], arr[i]];
        i++;
      }
    }
    [arr[i], arr[high]] = [arr[high], arr[i]];
    return i;
  }
  function sort(low, high) {
    if(low >= high) return;

    const pivotIndex = partition(low, high);
    sort(low, pivotIndex - 1);
    sort(pivotIndex + 1, high); 
  }
  sort(0, arr.length - 1);
  return arr;
}
Enter fullscreen mode Exit fullscreen mode

That's all folks!

Top comments (0)