Quick Sort Explained
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+1Pivot 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? +
Why is Quick Sort not stable? +
How do you avoid Quick Sort's worst case? +
See it in motion
Watch this algorithm and 9 others run step by step in our free interactive visualizer.
▶ Launch Visualiser