Sub topic 8
Stability and Why the Merge Uses <=
This chapter assumes you have already seen the merge function and top-down merge_sort from earlier chapters, and that you can read Python tuples and lambda expressions. The topic here is one character in the merge: the <= in if left[i] <= right[j]. That character decides whether merge sort is stable.
What Stability Means
A sorting algorithm is stable if elements that compare equal stay in the same relative order they had in the input. With plain integers you cannot see the difference, because one 2 looks like any other 2. Stability matters when you sort records by a key and the records differ in other fields.
Suppose you sort students by grade. Ana and Cy both have grade 2, and Ana comes first in the input. A stable sort guarantees Ana still comes before Cy in the output.
Where the Guarantee Comes From
Merge sort keeps equal elements in order because of two facts working together:
- Splitting preserves order.
items[:mid]holds the earlier elements anditems[mid:]holds the later ones. When two equal elements end up in different halves, the one that came first is always in the left half. - The merge breaks ties toward the left. When
left[i]andright[j]are equal,<=takesleft[i], the element that came first in the input.
Within each half, the recursive calls are stable by the same argument, so the order of equal elements survives every level. If you change <= to <, ties go to the right half, and equal elements from different halves come out reversed.
Seeing the Difference
The code below sorts records by a key function. The strict flag switches the tie rule between <= and <.
def merge_by_key(left, right, key, strict=False):
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 strict 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_by_key(items, key, strict=False):
if len(items) <= 1:
return list(items)
mid = len(items) // 2
return merge_by_key(
merge_sort_by_key(items[:mid], key, strict),
merge_sort_by_key(items[mid:], key, strict),
key,
strict,
)
students = [("Ana", 2), ("Ben", 1), ("Cy", 2), ("Dee", 1)]
grade = lambda s: s[1]
print(merge_sort_by_key(students, grade))
# [('Ben', 1), ('Dee', 1), ('Ana', 2), ('Cy', 2)]
print(merge_sort_by_key(students, grade, strict=True))
# [('Dee', 1), ('Ben', 1), ('Cy', 2), ('Ana', 2)]With <=, Ben stays ahead of Dee and Ana stays ahead of Cy. With <, the final merge combines [Ben, Ana] and [Dee, Cy]. Ben and Dee tie, so the strict rule takes Dee from the right first. The same thing happens with Ana and Cy. The output is still sorted by grade, but both pairs of equal records are swapped.
Why Anyone Cares
Stability lets you sort by several keys in separate passes. To order students by grade and then by name within each grade, sort by name first and then do a stable sort by grade. The second pass keeps the name order inside each grade group. Python's sorted and list.sort are stable for this reason. Both use Timsort, a merge-sort hybrid.
Common errors:
| Mistake | Effect |
|---|---|
| Using `<` in the merge | Equal elements from different halves come out reversed |
| Taking from the right on ties in any variant (bottom-up, linked list) | The same loss of stability |
| Splitting by interleaving (even and odd indices) | The left half no longer holds all the earlier elements, so `<=` no longer guarantees stability |
Exercise
You have a list of orders already sorted by timestamp. You want them grouped by customer ID, with each customer's orders still in timestamp order. Which single sort achieves this, and what would go wrong if the merge used < instead of <=?
Show answer
Do one stable sort by customer ID, for example merge sort with <=. Orders with the same customer ID keep their existing timestamp order. With <, orders for the same customer that land in different halves would come out in the wrong relative order, so some customers' orders would no longer be in timestamp order.
Exercise
Trace the strict (<) version on [("x", 1), ("y", 1)]. What is the output, and is it stable?
Show answer
The split gives [("x", 1)] and [("y", 1)]. In the merge, 1 < 1 is false, so ("y", 1) is taken first. The output is [("y", 1), ("x", 1)]. It is not stable, because x came before y in the input.