Sub topic 8
Stability and Why the Merge Uses <=
This chapter assumes you have read the earlier chapters on the merge step and on top-down merge sort. It also assumes you can read Python, follow recursion, and use tuples and lambda functions. Here we look at one property of merge sort that comes from a single character in the merge loop: the <= comparison.
What Stability Means
A sorting algorithm is stable if records with equal keys come out in the same relative order they went in. The key is the value you sort by. A record can hold much more than its key.
Suppose you sort these exam results by score:
| Original position | Name | Score |
|---|---|---|
| 0 | alice | 3 |
| 1 | bob | 1 |
| 2 | carol | 3 |
| 3 | dave | 2 |
| 4 | erin | 1 |
Bob and Erin both scored 1, and Bob comes first in the input. A stable sort must put Bob before Erin. Alice and Carol both scored 3, so Alice must come before Carol. An unstable sort may return either order for each tied pair.
Stability only matters when equal keys can be told apart. If you sort a plain list of integers, two 3s look the same, so their order cannot be observed. Once the records carry extra data, as rows in a table do, the order of ties becomes visible.
Why Stability Matters in Practice
The main use is multi-key sorting by successive passes. To sort by score, with ties broken alphabetically by name, you can:
- Sort by the secondary key (name).
- Stable-sort the result by the primary key (score).
The second pass keeps the alphabetical order inside each score group because it never reorders ties. Spreadsheets and table UIs rely on this when a user clicks one column header and then another. Without stability, the second click would scramble the first ordering.
Stability also keeps results predictable. If a sort is stable, the same input always produces the same output, even when keys tie. This makes tests and diffs easier to work with.
The Tie Rule in the Merge
Recall the core of the merge:
def merge(left, right):
result = []
i = j = 0
while i < len(left) and j < len(right):
if left[i] <= right[j]:
result.append(left[i])
i += 1
else:
result.append(right[j])
j += 1
result.extend(left[i:])
result.extend(right[j:])
return result
print(merge([1, 3, 5], [1, 2, 3])) # [1, 1, 2, 3, 3, 5]When left[i] and right[j] are equal, <= is true, so the element from left is taken first. That choice is the whole mechanism. The left half was cut from the front of the original slice, so every element in left appeared earlier in the input than every element in right. Taking from the left on a tie therefore keeps the earlier element earlier.
Change <= to < and a tie makes the condition false, so the right element goes first. The later element jumps ahead of the earlier one. The output is still sorted, so ordinary tests on integer lists will pass, but the sort is no longer stable.
Seeing It Happen with Records
The program below sorts records by a key function. A stable flag switches the tie rule, so you can compare the two results side by side.
def merge(left, right, key, stable=True):
result = []
i = j = 0
while i < len(left) and j < len(right):
a, b = key(left[i]), key(right[j])
take_left = a <= b if stable else a < b
if take_left:
result.append(left[i])
i += 1
else:
result.append(right[j])
j += 1
result.extend(left[i:])
result.extend(right[j:])
return result
def merge_sort(items, key=lambda x: x, stable=True):
if len(items) <= 1:
return list(items)
mid = len(items) // 2
return merge(
merge_sort(items[:mid], key, stable),
merge_sort(items[mid:], key, stable),
key,
stable,
)
records = [("alice", 3), ("bob", 1), ("carol", 3), ("dave", 2), ("erin", 1)]
by_score = lambda r: r[1]
print(merge_sort(records, by_score, stable=True))
# [('bob', 1), ('erin', 1), ('dave', 2), ('alice', 3), ('carol', 3)]
print(merge_sort(records, by_score, stable=False))
# [('erin', 1), ('bob', 1), ('dave', 2), ('carol', 3), ('alice', 3)]Both outputs are sorted by score. With <, though, every tied pair comes out reversed. On this input, each tie happens to meet at a merge where the later record sits in the right run, so the < rule swaps all of them.
Here is the multi-key pattern from earlier, built on the stable version:
def merge(left, right, key):
result = []
i = j = 0
while i < len(left) and j < len(right):
if key(left[i]) <= key(right[j]):
result.append(left[i])
i += 1
else:
result.append(right[j])
j += 1
result.extend(left[i:])
result.extend(right[j:])
return result
def merge_sort(items, key=lambda x: x):
if len(items) <= 1:
return list(items)
mid = len(items) // 2
return merge(merge_sort(items[:mid], key), merge_sort(items[mid:], key), key)
records = [("dave", 2), ("carol", 3), ("erin", 1), ("alice", 3), ("bob", 1)]
step1 = merge_sort(records, key=lambda r: r[0]) # secondary key: name
step2 = merge_sort(step1, key=lambda r: r[1]) # primary key: score
print(step2)
# [('bob', 1), ('erin', 1), ('dave', 2), ('alice', 3), ('carol', 3)]Within score 1, Bob comes before Erin. Within score 3, Alice comes before Carol. Both orders survive from the name pass.
Why the Whole Sort Is Stable
Taking from the left on ties is necessary, but you still need to show the full recursive sort is stable. Use induction on the length of the slice, the same way the correctness chapter did.
Take two records x and y with equal keys, where x comes before y in the input slice. You need to show that x comes before y in the output.
- Base case. A slice of length 0 or 1 has no such pair.
- Both in the same half. By the induction hypothesis, the recursive call keeps x before y within that half. The merge takes elements from each run strictly from front to back, so their order within the run is kept.
- x in the left half, y in the right half. This is the only other case, because the split is contiguous and x comes first. While y is at the front of the right run, x is either already in the output or still in the left run. If x is still waiting, every left element from the current front up to x has a key no greater than x's key, because the left run is sorted, and x's key equals y's key. So each comparison against y is a
<=tie or a win for the left element, and the merge keeps taking from the left until x is output. Then y follows.
The case where y is in the left half and x is in the right half cannot happen. It would need the split to put a later element on the left, and a contiguous split never does that.
Common Ways to Break Stability by Accident
| Mistake | Why it breaks stability |
|---|---|
| Using `<` in the merge | Ties take the right element, which came later in the input. |
| Splitting by even and odd index (`items[::2]`, `items[1::2]`) | The left half no longer holds only earlier elements, so "take left on ties" no longer means "take the earlier one". |
| Merging runs out of order in a bottom-up or k-way merge | If a later run is treated as the "left" input, ties favor the wrong records. |
| Sorting ascending, then reversing the result to get descending order | Reversal flips the order of tied records too. |
| Comparing whole records when you meant to compare keys | Ties are broken by the other fields, so the result reflects those fields and not the input order. |
The even/odd split deserves a closer look because it looks harmless. For [("a", 1), ("b", 1), ("c", 1)], the even half is [a, c] and the odd half is [b]. A merge that takes from the left on ties outputs a, c, b, and c has jumped ahead of b.
For descending order, keep the stable comparison and invert the key, for example key=lambda r: -r[1], or flip the comparison so that ties still take from the left. Python's built-in sorted(..., reverse=True) is documented to keep ties in their original order, so it does not simply reverse an ascending sort.
Exercises
Exercise
A teammate's merge sort uses if right[j] < left[i]: take right, else: take left. Is this stable? Explain.
Show answer
Yes. On a tie, right[j] < left[i] is false, so the else branch takes from the left. This is the same as left[i] <= right[j]. What matters is which side wins a tie, not how the condition is written.
Exercise
Trace the unstable (<) merge sort on [("p", 5), ("q", 5)]. What is the output, and why?
Show answer
The halves are [("p", 5)] and [("q", 5)]. At the single comparison, 5 < 5 is false, so ("q", 5) is taken first. The output is [("q", 5), ("p", 5)], which reverses the input order of the tied pair.
Exercise
Write a test that detects instability. Given a sort function f(items, key), check whether it is stable on random records with many duplicate keys.
Show answer
Tag each record with its index, sort by key, then verify the indexes within each key group: import random def isstable(f, trials=200): for in range(trials): data = [(random.randint(0, 3), idx) for idx in range(20)] out = f(data, key=lambda r: r[0]) for a, b in zip(out, out[1:]): if a[0] == b[0] and a[1] > b[1]: return False return True Using few distinct keys (0 to 3) creates many ties, so an unstable sort is very likely to fail at least one trial.
Exercise
You need a list sorted by department ascending, and by salary descending within each department, using only a stable sort that accepts a key. Which two passes do you run, and in what order?
Show answer
First sort by salary descending, for example with key=lambda r: -r.salary. Then stable-sort by department ascending. The second pass keeps the salary order inside each department because it never reorders records whose departments tie.