Algorithm Deep Dives

Quick Sort Explained

Updated June 8, 2026 7 min read

Quick Sort is the fastest general-purpose sorting algorithm in practice for in-memory data, thanks to excellent cache behavior and tight inner loops. It is a divide-and-conquer algorithm built around a single clever operation: partitioning around a pivot.

How Quick Sort works

Pick a pivot element. Partition the array so that everything smaller than the pivot ends up to its left and everything larger to its right — now the pivot is in its final position. Then recursively apply the same process to the left and right partitions. When the partitions shrink to size one, the array is sorted.

Pseudocode

quickSort(a, lo, hi):
  if lo < hi:
    p = partition(a, lo, hi)
    quickSort(a, lo, p-1)
    quickSort(a, p+1, hi)

partition(a, lo, hi):
  pivot = a[hi]
  i = lo - 1
  for j from lo to hi-1:
    if a[j] < pivot:
      i++; swap(a[i], a[j])
  swap(a[i+1], a[hi])
  return i+1

Pivot selection is everything

Quick Sort averages O(n log n) but degrades to O(n²) when the pivot is consistently the smallest or largest element — which naive 'always pick the last element' does on sorted input. The fixes are randomized pivots or median-of-three (pivot = median of first, middle, last). These make the worst case astronomically unlikely. It is in-place (O(log n) stack) but not stable.

Why it beats Merge Sort in practice

Both are O(n log n), but Quick Sort sorts in-place with contiguous memory access, so it stays in CPU cache and avoids the allocation overhead of Merge Sort. That is why it is typically 2-3x faster on arrays that fit in memory. Read the full analysis in Why Quick Sort is faster than Merge Sort.

Frequently asked questions

What is the time complexity of Quick Sort? +
Quick Sort is O(n log n) on average and best case, but O(n²) in the worst case with poor pivot selection. Randomized or median-of-three pivots make the worst case extremely rare.
Why is Quick Sort not stable? +
Partitioning swaps elements across long distances, which can change the relative order of equal keys. A stable version is possible but requires O(n) extra space.
How do you avoid Quick Sort's worst case? +
Use a randomized pivot or the median-of-three method, and fall back to Heap Sort if recursion gets too deep (this hybrid is called Introsort).

See it in motion

Watch this algorithm and 9 others run step by step in our free interactive visualizer.

▶ Launch Visualiser

Related articles

← Back to all articles