Community Python Snippet

Quick Sort in Three Lines, and Why It's Wrong

Every interview blog shows the cute three-line quicksort. It's a teaching aid that looks elegant and ships bugs: O(n log n) extra memory, quadratic on sorted input, and unstable. Here is the cute version, the in-place version we should actually write, and the version with a randomized pivot.

Quick Sort in Three Lines, and Why It's Wrong

Every interview blog shows the cute three-line quicksort. It's a teaching aid that looks elegant and ships bugs: O(n log n) extra memory, quadratic on sorted input, and unstable. Here is the cute version, the in-place version we should actually write, and the version with a randomized pivot.

Python
Compiler
3 snippets
quick-sort
sorting
code-template
algorithms
nathanmurphy

By @nathanmurphy

February 13, 2026

·

Updated May 20, 2026

479 views

4

Rate

The three-line version is real code I have seen in code reviews and even in shipping production scripts. It is a useful teaching aid because the recursion structure is unusually visible, but every list comprehension allocates a fresh list, doubling the asymptotic memory. The bigger problem is the pivot choice: xs[0] on already-sorted input puts every element into greater and the recursion depth becomes O(n), which on a 10k-element sorted list will overflow Python's default recursion limit. The third problem (instability) only matters when sorting tuples by one field while preserving the order of another, but it is the same root cause: equal elements get hoisted into the equal bucket out of input order.