Partition the possibility.
Split around a pivot and distinguish a teaching implementation from an in-place one.
01 The idea
Quicksort partitions values around a pivot, then sorts the partitions. Balanced partitions lead to O(n log n) work; repeatedly unbalanced partitions can produce quadratic work and deep recursion. This readable three-way teaching version allocates new lists, so it is not the low-extra-memory in-place partition algorithm sometimes associated with quicksort.
02 The experiment
Read it once. Predict what will happen. Then copy it into a .py file and run it in your local Python setup.
def quicksort(values):
if len(values) < 2: return list(values)
pivot = values[len(values) // 2]
low = [value for value in values if value < pivot]
equal = [value for value in values if value == pivot]
high = [value for value in values if value > pivot]
return quicksort(low) + equal + quicksort(high)
print(quicksort([4, 1, 3, 4, 2]))[1, 2, 3, 4, 4]
03 Under the hood
- 1
The pivot separates lower, equal, and higher values. Grouping equal values avoids repeatedly recursing over identical keys.
- 2
Choosing the middle-position value is not the same as finding the median value. It does not guarantee balanced partitions.
- 3
The implementation assumes a consistent total ordering. Special values such as floating-point NaN do not behave like ordinary ordered numbers and can violate its classification assumptions.
04 Your turn, builder
Check that repeated identical values are retained and an empty input remains empty.
Reveal one possible solution +
def quicksort(values):
if len(values) < 2: return list(values)
pivot = values[len(values) // 2]
return quicksort([x for x in values if x < pivot]) + [x for x in values if x == pivot] + quicksort([x for x in values if x > pivot])
assert quicksort([2, 2, 2]) == [2, 2, 2]
assert quicksort([]) == []
print("Quicksort checks passed")05 Check your signal
Does choosing the middle-position pivot guarantee balanced partitions?
Experiment. Logged.
When you can explain the idea and make the example your own, mark it complete. Your log stays in this browser.
Keep exploring
Go deeper with the official Python guide ↗.