Sub topic 2
In-Place but Not Stable
This chapter assumes you know Big-O notation and recursion, and that you have read the Lomuto quicksort from the previous chapter.
In-Place but Not Stable
Quicksort is in-place: it rearranges the array by swapping elements and needs no second array. Its only extra memory is the recursion stack.
Quicksort is not stable. A stable sort keeps equal keys in their original order. Lomuto's long-range swaps can move an element past an equal one. For example, if you sort (2,'a'), (2,'b'), (1,'c') by number with the last element as the pivot, the pivot 1 swaps with (2,'a'). The result is (1,'c'), (2,'b'), (2,'a'), so the two 2s have changed order. If you need stability, use merge sort or Python's built-in sorted.
How Fast Is Quicksort? Best, Average, and Worst Case
Partitioning a range of n elements takes n − 1 comparisons. The total cost depends on how evenly each pivot splits its range.
| Case | Split | Recurrence | Cost |
|---|---|---|---|
| Best | Halves | T(n) = 2T(n/2) + n | O(n log n) |
| Average | Random | Averaged over pivot rank | about 1.39 n log₂ n, O(n log n) |
| Worst | 0 and n − 1 | T(n) = T(n − 1) + n | about n²/2, O(n²) |
In the average case, even a lopsided 90/10 split still produces only O(log n) levels of recursion. The worst case comes from splits that are completely one-sided at every level.
When Quicksort Goes Quadratic
Take the last-element pivot. On input that is already sorted, the pivot is always the maximum. Every partition then peels off a single element, which produces the worst case. Reverse-sorted input does the same thing, and so does an array where every key is equal: Lomuto's < test sends all of them to one side. The recursion also reaches depth n, so a large sorted input can overflow Python's recursion limit.
Choosing a Good Pivot
A fixed position, such as first, last, or middle, always has some input that defeats it. There are two common fixes:
- Median-of-three: use the median of the first, middle, and last elements. This handles sorted input well.
- Random pivot: no single input is reliably bad.
Randomized Quicksort
Before partitioning, swap a uniformly random element into the pivot slot:
import random
def lomuto_partition(a, lo, hi):
pivot = a[hi]
i = lo
for j in range(lo, hi):
if a[j] < pivot:
a[i], a[j] = a[j], a[i]
i += 1
a[i], a[hi] = a[hi], a[i]
return i
def randomized_partition(a, lo, hi):
r = random.randint(lo, hi)
a[r], a[hi] = a[hi], a[r]
return lomuto_partition(a, lo, hi)
def rquicksort(a, lo, hi):
if lo < hi:
p = randomized_partition(a, lo, hi)
rquicksort(a, lo, p - 1)
rquicksort(a, p + 1, hi)
data = list(range(500))
rquicksort(data, 0, len(data) - 1)
print(data[:5]) # [0, 1, 2, 3, 4]The expected time is now O(n log n) on every input. A slow run can still happen, but only through bad luck, and that luck does not depend on the input.
Exercise
Quicksort with a last-element pivot runs on a sorted array of 1,000 elements. How many comparisons does it make?
Show answer
The partitions cost 999 + 998 + ... + 1 = 999·1000/2 = 499,500 comparisons.
Exercise
Why does a random pivot make quicksort's expected running time independent of the input order?
Show answer
The pivot's rank in each range is uniformly random no matter how the input is arranged, so the same O(n log n) average analysis applies to every input.