quicksort in javascript

Here is a simple implementation of the quicksort algorithm in JavaScript:

index.tsx
function quicksort(arr) {
  if (arr.length <= 1) {
    return arr;
  }

  const pivot = arr[Math.floor(arr.length / 2)];
  const left = [];
  const right = [];

  for (let i = 0; i < arr.length; i++) {
    if (arr[i] < pivot) {
      left.push(arr[i]);
    } else if (arr[i] > pivot) {
      right.push(arr[i]);
    }
  }

  return [...quicksort(left), pivot, ...quicksort(right)];
}

// Example usage
const unsortedArr = [8, 3, 10, 1, 9, 7, 6, 4];
const sortedArr = quicksort(unsortedArr);
console.log(sortedArr); // [1, 3, 4, 6, 7, 8, 9, 10]
544 chars
25 lines

The function first checks if the array has one or zero elements, in which case it is already sorted and can simply be returned. Otherwise, it chooses a "pivot" element and partitions the array into two sub-arrays, according to whether they are less than or greater than the pivot. Finally, it recursively sorts the sub-arrays and combines them with the pivot to produce the final sorted array.

gistlibby LogSnag