Sub topic 5
In-Place but Not Stable
This chapter assumes you already know the recursive Lomuto quicksort from the previous chapter. You should also be comfortable with Python tuples and lambdas, and know what Big-O means for memory as well as time.
Two properties shape how a sorting algorithm is used in practice. The first is how much extra memory it needs. The second is whether it keeps equal elements in their original order. Quicksort does well on the first and poorly on the second. That combination explains why some libraries use quicksort for numbers but not for records.
What "in-place" means
An in-place sort rearranges elements inside the input array. Its extra memory is small compared with n. The strict definition allows O(1) auxiliary space. In practice, the term also covers algorithms whose only overhead is a recursion stack of O(log n) frames.
The Lomuto quicksort fits the practical definition. Each partition step uses a few index variables (i, j, lo, hi) and swaps elements where they sit. No second array is ever allocated. The only memory that grows with n is the call stack:
| Situation | Stack depth | Auxiliary memory |
|---|---|---|
| Balanced splits | about log₂ n | O(log n) |
| Random pivots, expected | O(log n) | O(log n) |
| Worst case (every split is 0 and n−1) | n | O(n) |
The worst-case row matters. A naive quicksort on a bad input can use linear stack space and, in Python, can hit the recursion limit. A later chapter, "Bounding Recursion Depth", shows how to cap the stack at O(log n) in every case. For now, think of quicksort as "in-place, apart from the stack".
The list-comprehension version from the first chapter, quicksort_simple, is not in-place. Each call builds new less, equal, and greater lists, so it allocates O(n) memory per recursion level that is alive at once. It is easier to read, but it gives up the memory advantage.
What "stable" means
A sort is stable if two elements with equal keys come out in the same relative order they went in. The key is the part of the element the sort compares. For plain integers stability cannot be observed, because two equal integers are indistinguishable. It matters when elements carry extra data, such as (age, name) records sorted by age alone.
Stability matters most when you sort in several passes. Suppose you sort employees by name and then sort by department with a stable sort. Within each department, the names stay alphabetical. With an unstable sort, the second pass can scramble the first pass's work.
Watching Lomuto break stability
The code below is the Lomuto quicksort from earlier, with one change: it compares key(x) instead of x. That lets it sort records by one field.
def lomuto_partition_by(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(a, key, lo=0, hi=None):
if hi is None:
hi = len(a) - 1
if lo < hi:
p = lomuto_partition_by(a, lo, hi, key)
quicksort_by(a, key, lo, p - 1)
quicksort_by(a, key, p + 1, hi)
records = [(5, 'a'), (5, 'b'), (5, 'c'), (1, 'd'), (3, 'p')]
quicksort_by(records, key=lambda r: r[0])
print(records)
# [(1, 'd'), (3, 'p'), (5, 'b'), (5, 'c'), (5, 'a')]
print(sorted([(5, 'a'), (5, 'b'), (5, 'c'), (1, 'd'), (3, 'p')],
key=lambda r: r[0]))
# [(1, 'd'), (3, 'p'), (5, 'a'), (5, 'b'), (5, 'c')]The three records with key 5 started in the order a, b, c and came out as b, c, a. Python's built-in sorted is stable and keeps a, b, c.
Here is the trace that produces the scrambling:
- First partition, range 0..4, pivot key 3. Indices 0–2 hold key 5, so nothing moves. At
j = 3, key 1 < 3, so(1,'d')swaps witha[0]. That sends(5,'a')from the front to index 3, pastbandc. The final swap places the pivot at index 1, which moves(5,'b')to the end. The array is now[(1,'d'), (3,'p'), (5,'c'), (5,'a'), (5,'b')]. - Partition range 2..4, pivot
(5,'b'). No key is strictly less than 5, so the final swap exchanges index 2 and index 4. The array is now[..., (5,'b'), (5,'a'), (5,'c')]. - Partition range 3..4, pivot
(5,'c'). The final swap exchanges the two, giving[..., (5,'b'), (5,'c'), (5,'a')].
The cause is visible in step 1. A swap exchanges two elements that can be far apart, and it ignores everything in between. When (5,'a') jumped from index 0 to index 3, it passed over two elements with the same key, and nothing recorded that order. Hoare partitioning, covered later, has the same weakness because it also swaps elements across long distances.
Why the simple version is stable
quicksort_simple is stable if it compares by key. The list comprehensions scan the input from left to right, so less, equal, and greater each keep the original relative order. Concatenating the recursive results never moves an element past another element with the same key. Stability here comes from copying into new lists, and copying is exactly what in-place partitioning avoids. This is the trade-off in general. Stable sorting usually needs O(n) extra memory or extra time.
Making quicksort stable when you must
The standard workaround is decoration. You attach each element's original index, sort by (key, index), and then strip the index off. Because every (key, index) pair is unique, no two decorated elements are equal, so instability has no effect on the result.
# Continues from the previous block (uses quicksort_by).
def stable_quicksort_by(a, key):
decorated = [(key(x), i, x) for i, x in enumerate(a)]
quicksort_by(decorated, key=lambda t: (t[0], t[1]))
a[:] = [t[2] for t in decorated]
records = [(5, 'a'), (5, 'b'), (5, 'c'), (1, 'd'), (3, 'p')]
stable_quicksort_by(records, key=lambda r: r[0])
print(records)
# [(1, 'd'), (3, 'p'), (5, 'a'), (5, 'b'), (5, 'c')]The decorated list costs O(n) extra memory, so the result is no longer in-place. If you need stability, a stable algorithm built for it, such as merge sort or Timsort, is usually the better choice.
Choosing between properties
| Algorithm | In-place | Stable | Typical extra memory |
|---|---|---|---|
| Quicksort (Lomuto or Hoare) | Yes | No | O(log n) stack |
| `quicksort_simple` (list-building) | No | Yes, with key comparison | O(n) |
| Insertion sort | Yes | Yes | O(1) |
| Heapsort | Yes | No | O(1) |
| Merge sort | No | Yes | O(n) |
| Timsort (Python `sorted`, `list.sort`) | No | Yes | Up to O(n) |
Real libraries split along this line. Java's Arrays.sort uses a dual-pivot quicksort for primitive arrays such as int[], where stability cannot be observed. It uses Timsort for object arrays, where it can. C++ gives you std::sort, which is unstable and in practice an introsort, and std::stable_sort as a separate function. Python chose stability for every sort and accepts the memory cost.
A practical rule follows from this:
- Sort primitives, or records whose keys are unique: an unstable in-place sort is fine.
- Sort records in several passes, or when users can see the order of ties: use a stable sort.
- Memory is tight and you also need stability: decorate with indices only if O(n) extra is acceptable. Otherwise, consider in-place merge variants, which are much slower in practice.
Common mistakes
- Calling quicksort "O(1) space". The recursion stack is part of its memory use and can reach O(n) without depth control.
- Concluding that a sort is stable because one small test passed. Use inputs with many repeated keys.
- Making quicksort "stable" by changing
<to<=in Lomuto. That does not fix the long-distance swaps. It also puts every equal key on one side of the pivot, which makes inputs with many duplicates slower. - Assuming the language's default sort is unstable, or stable, without checking its documentation.
Exercise
Run the Lomuto quicksort_by from this chapter on [(2, 'x'), (2, 'y'), (1, 'z')], sorting by the first field. Trace each partition and give the final list. Is the result stable for this input, and does that prove the algorithm is stable?
Show answer
First partition (range 0..2, pivot key 1): no key is less than 1, so i stays 0 and the final swap exchanges indices 0 and 2, giving [(1,'z'), (2,'y'), (2,'x')] with p = 0. Second partition (range 1..2, pivot (2,'x')): 2 < 2 is false, so the final swap exchanges indices 1 and 2, giving [(1,'z'), (2,'x'), (2,'y')]. The output happens to be stable, because the two swaps reversed each other. This does not prove stability. The five-element example in this chapter shows that the same code reorders three equal keys.
Exercise
A colleague sorts a list of orders by customer name and then calls an in-place Lomuto quicksort to sort the same list by order date. They expect orders on the same date to stay in name order. What goes wrong, and name two ways to fix it.
Show answer
Lomuto quicksort is unstable, so orders with the same date can come out in any name order. The first sort's work is lost. Fix 1: use a stable sort, such as Python's list.sort, for the second pass. Fix 2: do a single sort with a compound key (date, name), which needs no stability at all. A third option is to decorate each element with its index before the date sort, at the cost of O(n) extra memory.
Exercise
Why is it reasonable for Java to use an unstable quicksort for int[] but not for arrays of objects?
Show answer
Two equal ints cannot be told apart, so reordering them has no visible effect, and the in-place quicksort's speed and low memory use cost nothing. Objects that compare equal on the sort key can differ in their other fields, so an unstable sort could visibly reorder them. Java therefore uses the stable Timsort for object arrays.