Quick Sort

Picks a pivot, partitions around it, and recursively sorts the partitions. One of the fastest general-purpose sorts in practice.

Best O(n log n) Avg O(n log n) Worst O(n²) Space O(log n) Stable No In-place Yes Comparison-based

How it works

Quick Sort picks a pivot, partitions the array so that everything smaller sits left of the pivot and everything larger sits right, then recurses into each side. The pivot lands in its final position after each partition.

With a good pivot the partitions are balanced and the algorithm runs in O(n log n); a degenerate pivot on already-sorted data can degrade to O(n^2), which is why real implementations randomize or use median-of-three pivots.

Implementation

function quickSort(arr, lo = 0, hi = arr.length - 1) {
  if (lo >= hi) return;
  const pivot = arr[hi];
  let i = lo - 1;
  for (let j = lo; j < hi; j++) {
    if (arr[j] < pivot) {
      i++;
      [arr[i], arr[j]] = [arr[j], arr[i]];
    }
  }
  [arr[i+1], arr[hi]] = [arr[hi], arr[i+1]];
  quickSort(arr, lo, i);
  quickSort(arr, i + 2, hi);
}

Advantages

  • Fastest general-purpose comparison sort in practice for in-memory arrays.
  • In-place with only O(log n) stack space.
  • Very cache-friendly due to its sequential partition scans.

Disadvantages

  • Worst case is O(n^2) without pivot safeguards.
  • Not stable in its classic form.

When to use it

The default for unstable, in-memory sorting of primitives. Use IntroSort (Quick Sort with a heapsort fallback) when you need the average-case speed but a worst-case guarantee.