Quick Sort

by Abhishek Kumar

JavaScript

function partition(arr, start, end) {
  // Taking the last element as the pivot
  const pivot = arr[end];
  let p = start;
  for (let i = start; i < end; i++) {
    if (arr[i] < pivot) {
      // Swapping elements
      [arr[i], arr[p]] = [arr[p], arr[i]];
      // Moving to next element
      p++;
    }
  }

  // Putting the pivot value in the middle
  [arr[p], arr[end]] = [arr[end], arr[p]]
  return p;
}

function quickSort(arr, start, end) {
  // Base case or terminating case
  if (start >= end) {
    return;
  }

  // Returns pivotIndex
  let pivotIndex = partition(arr, start, end);

  // Recursively apply the same logic to the left and right subarrays
  quickSort(arr, start, pivotIndex - 1);
  quickSort(arr, pivotIndex + 1, end);
}

array = [7, -2, 4, 1, 6, 5, 0, -4, 2];
quickSort(array, 0, array.length - 1);

console.log(array);