Sub topic 5
In-Place but Not Stable
This chapter assumes you can read the recursive Lomuto quicksort from the previous chapter, you know Big-O notation, and you know what a tuple key is in Python. It covers two properties people often mix up when choosing a sort: whether the sort needs extra memory, and whether it keeps equal elements in their original order.
What "in-place" means for quicksort
A sort is in-place if it rearranges elements inside the input array and needs only a small amount of extra memory. Lomuto partitioning qualifies. It uses a few index variables and swaps elements within a[lo..hi]. It never allocates a second array.
There is one hidden cost, which is the recursion stack. Each pending call holds its own lo and hi. With balanced partitions the stack grows to O(log n) frames. With badly unbalanced partitions it can grow to O(n). A later chapter, "Bounding Recursion Depth", shows how to cap it at O(log n). By comparison, the simple list-building version from the first chapter allocates new lists at every level, so it is not in-place.
What "stable" means
A sort is stable if elements with equal keys come out in the same relative order they went in. Stability only matters when records carry more than their key. For example, you might sort orders by date when they were already sorted by customer.
Quicksort as written is not stable. The code below sorts records by their first field.
def lomuto_partition_by_key(a, lo, hi, key):
pivot = key(a[hi])
i = lo
for j in range(lo, hi):
if key(a[j]) < pivot:
a[i], a[j] = a[j], a[i]
i += 1
a[i], a[hi] = a[hi], a[i]
return i
def quicksort_by_key(a, key, lo=0, hi=None):
if hi is None:
hi = len(a) - 1
if lo < hi:
p = lomuto_partition_by_key(a, lo, hi, key)
quicksort_by_key(a, key, lo, p - 1)
quicksort_by_key(a, key, p + 1, hi)
original = [(2, 'a'), (1, 'b'), (2, 'c'), (1, 'd')]
records = list(original)
quicksort_by_key(records, key=lambda r: r[0])
print(records) # [(1, 'd'), (1, 'b'), (2, 'a'), (2, 'c')]
print(sorted(original, key=lambda r: r[0])) # [(1, 'b'), (1, 'd'), (2, 'a'), (2, 'c')]In the input, 'b' comes before 'd'. Quicksort reverses that order. Python's built-in sorted preserves it.
Why the order breaks
Partitioning swaps elements over long distances. In the first pass the pivot is (1, 'd'). No element has a key less than 1, so the final swap moves (1, 'd') from index 3 to index 0. That jump carries it past (1, 'b'), and nothing ever moves it back.
Getting stability back
You can make quicksort stable by sorting on the pair (key, original_index). Every pair is then distinct, so ties cannot be reordered. The catch is that you have to store n indices, which means O(n) extra memory. At that point the sort is no longer in-place, and merge sort or Timsort is usually the better choice.
| Algorithm | Extra memory | Stable |
|---|---|---|
| Quicksort (Lomuto or Hoare) | O(log n) stack, expected | No |
| Heapsort | O(1) | No |
| Insertion sort | O(1) | Yes |
| Merge sort / Timsort | O(n) | Yes |
Exercise
You need to sort a large array of plain 64-bit integers using as little memory as possible. Does quicksort's instability matter here?
Show answer
No. Equal integers cannot be told apart, so their relative order cannot be observed. Instability only matters when records carry data beyond the sort key.
Exercise
Sorting the records with key=lambda r: (r[0], original.index(r)) appears to make quicksort stable. What are two problems with this approach?
Show answer
First, list.index does a linear scan for every comparison, so the sort becomes far slower than O(n log n). Second, index returns the first match, so duplicate records get the same index and ties are still not broken. Precompute pairs with enumerate instead. That costs O(n) extra memory, so the sort is no longer in-place.