Skip to main content

Quick Sort

Partition around a pivot (last element of each range), then recurse, the pivot lands in its final home.

time O(n log n) avg, O(n²) worstspace O(log n)Read the lesson
AdvancedO(n log n) avg, O(n²) worst

Partition around a pivot (last element of each range), then recurse, the pivot lands in its final home.

step 1 / 21

What's happening

Quick sort: pick a pivot (last element here), move smaller values left of it and larger right, then recurse into both sides.

comparisons: 0swaps: 0writes: 0
comparingswappingkey heldwritingpivotfinal position

P marks the pivot (last element of the range); B marks the boundary of the “smaller” region. After partitioning, the pivot sits at its final index forever. Try sorted input to trigger the O(n²) worst case.

Understand the algorithm

time O(n log n) avg, O(n²) worstspace O(log n)

What it is

Quick sort partitions the array around a pivot, smaller values left, larger right, placing the pivot at its final home, then recurses on both sides.

Why it matters

It is the most-used general-purpose sort in practice (C's qsort, C++ introsort core) because its partitioning is cache-friendly and its constants are tiny. It also teaches the biggest lesson in algorithm engineering: pivot choice turns an O(n log n) average into an O(n²) worst case.

How it works

  1. 1Choose a pivot (here: the last element of the range).
  2. 2Sweep the range, moving every value smaller than the pivot to the left region.
  3. 3Swap the pivot just after that region, it is now at its final sorted index.
  4. 4Recurse on the left and right parts; ranges of size ≤ 1 are done.

Real-world uses

  • General-purpose in-memory sorting (language runtimes, database engines)
  • Quickselect, the same partitioning finds the k-th smallest in O(n) average
  • Situations needing in-place sorting with small constants

Strengths

  • O(n log n) average with the best cache behavior of comparison sorts
  • In place, O(log n) stack, no buffers
  • Partitioning is a reusable primitive (quickselect, 3-way partition)

Limitations

  • O(n²) worst case on adversarial/sorted input with a naive pivot
  • Not stable
  • Recursion depth can hit O(n) without tail-call handling or median-of-three

Try sorted input to see the worst case unfold with the naive pivot.