Partition the possibility.
Split around a pivot and distinguish a teaching implementation from an in-place one.
01 Model 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.
Every value belongs to the partition defined by its relation to the pivot.
02 State the strategy
Read the steps independently of syntax. Explain what each step preserves before translating it into code.
CHOOSE a pivot
PARTITION into smaller, equal, larger values
SORT smaller and larger partitions
CONCATENATE03 Make it concrete
The implementation uses Python 3.11+ with only the standard library. Run it locally, or download the independent DSA workbench.
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]
- 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 Count the cost
O(n log n) with balanced partitions; O(n²) worst case
O(n) balanced; O(n²) worst-case peak for this copying version
Bounds refer to the shown implementation and exclude printed output unless stated. n is input size; V and E are graph vertices and edges.
05 Your next move
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")06 Check your reasoning
Does choosing the middle-position pivot guarantee balanced partitions?
Understand it. Then own it.
Can you explain the invariant, trace an edge case, and defend the cost model? Log the experiment when the reasoning makes sense.