Sub topic 6
Which Classic Algorithms Are Stable, and Why
This chapter assumes you can read Python and already know what a stable sort is. A stable sort keeps elements with equal keys in their original input order. Here we look at how each classic algorithm moves elements, because that movement decides whether it is stable.
The general rule
An algorithm is stable if it never moves an element past another element with an equal key. Algorithms that only compare and move neighbors, or that merge in order, tend to be stable. Algorithms that swap elements across long distances tend to be unstable, because a long swap can jump one element over an equal one without ever comparing the two.
| Algorithm | Stable? | Reason |
|---|---|---|
| Insertion sort | Yes | Shifts only past strictly greater keys |
| Bubble sort | Yes | Swaps neighbors only when strictly out of order |
| Merge sort | Yes | Takes from the left half when keys tie |
| Selection sort | No | Swaps the minimum into place over a long distance |
| Quicksort | No | Partitioning swaps elements across the array |
| Heapsort | No | Heap operations reorder equal keys freely |
Insertion sort: stable because of a strict comparison
def insertion_sort(items, key):
for i in range(1, len(items)):
current = items[i]
j = i - 1
# Strict '>' never moves an element past an equal one, which keeps the sort stable.
while j >= 0 and key(items[j]) > key(current):
items[j + 1] = items[j]
j -= 1
items[j + 1] = current
return items
print(insertion_sort([(2, "a"), (1, "b"), (2, "c")], key=lambda r: r[0]))
# [(1, 'b'), (2, 'a'), (2, 'c')]The inner loop stops as soon as it meets a key equal to current, so current stays behind it. If you change > to >=, the loop moves equal elements as well, and the sort becomes unstable. Stability depends on this one character in the implementation as well as on the algorithm.
Merge sort: stable because ties go left
Merge sort splits the list, sorts each half, then merges the halves. The left half holds elements that came earlier in the input. When the two front elements tie, taking the left one keeps input order.
def merge_sort(items, key):
if len(items) <= 1:
return items
mid = len(items) // 2
left = merge_sort(items[:mid], key)
right = merge_sort(items[mid:], key)
out, i, j = [], 0, 0
while i < len(left) and j < len(right):
if key(left[i]) <= key(right[j]): # '<=' prefers the left side on ties
out.append(left[i]); i += 1
else:
out.append(right[j]); j += 1
out.extend(left[i:])
out.extend(right[j:])
return out
print(merge_sort([(2, "a"), (1, "b"), (2, "c"), (1, "d")], key=lambda r: r[0]))
# [(1, 'b'), (1, 'd'), (2, 'a'), (2, 'c')]Here the comparison runs the other way. Merge sort needs <=, and writing < would take from the right on ties and break stability. Merge sort pays for this guarantee with O(n) extra memory for the merged output.
Quicksort: unstable because of partitioning
Lomuto partitioning picks the last element as the pivot. It moves smaller keys to the front and then swaps the pivot into place. Take the input [(2,a), (2,b), (1,c)] with pivot (1,c). No element is smaller than the pivot, so the pivot swaps with index 0:
The swap moved (2,a) past (2,b), and the algorithm never compared the two. Stable quicksort variants exist, but they need extra memory, which removes quicksort's main advantage of sorting in place.
Heapsort and selection sort
Heapsort repeatedly swaps the root of the heap with the last unsorted slot. With [(1,a), (1,b)], the heap is already valid, so the first extraction swaps them and the output is b, a. Selection sort fails the same way. It finds the minimum and swaps it to the front, and the element it displaces can land behind an equal key.
Exercise
Bubble sort swaps adjacent elements when key(items[j]) > key(items[j+1]). Is it stable, and what single change would make it unstable?
Show answer
It is stable, because it swaps only neighbors that are strictly out of order, so equal keys never pass each other. Changing the condition to '>=' would swap equal neighbors and make it unstable.
Exercise
Run selection sort on [(3,x), (3,y), (1,z)]. What is the output, and does it show instability?
Show answer
The minimum (1,z) swaps with index 0, giving [(1,z), (3,y), (3,x)]. The remaining part is already in order by key. The final output has y before x, which shows the sort is unstable.