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 August 19, 2026

480 views

4

Rate

from __future__ import annotations

# The version that fits in a tweet. Looks like Haskell. Hides three problems:
#   1. O(n log n) extra memory: every recursion allocates two new lists.
#   2. O(n^2) on sorted/reverse-sorted input because xs[0] is always the worst pivot.
#   3. Unstable: equal elements can be reordered relative to their input order.

def quicksort_cute(xs):
    if len(xs) <= 1:
        return xs
    pivot = xs[0]
    less = [x for x in xs[1:] if x < pivot]
    equal = [x for x in xs if x == pivot]
    greater = [x for x in xs[1:] if x > pivot]
    return quicksort_cute(less) + equal + quicksort_cute(greater)

import random
random.seed(0)
random_input = [random.randint(0, 100) for _ in range(20)]
sorted_input = list(range(20))

print('random  ->', quicksort_cute(random_input))
print('sorted  ->', quicksort_cute(sorted_input))

# Show the worst-case behavior: depth on already-sorted input.
import sys
sys.setrecursionlimit(50)
longest = list(range(40))
try:
    quicksort_cute(longest)
    print('40 sorted: completed')
except RecursionError as e:
    print('40 sorted: RecursionError (worst-case depth)')

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.