Sub topic 1
What a Comparison Sort Does
Prerequisites
This chapter assumes you can write basic code in a mainstream language and work with lists and records. It also assumes you can read Big-O notation and pass a function or lambda as an argument.
Comparison Sorting
A comparison sort puts elements in order by asking one question again and again: "does a come before b?" It never looks at the inside of a value, only at the answers to these comparisons. Any comparison sort needs Ω(n log n) comparisons in the worst case. Merge sort, quicksort, heapsort and insertion sort are all comparison sorts.
Keys, Comparators and Equal Elements
A sort key is the part of a record you sort by, such as a score or a last name. A comparator is a function that decides the order of two elements. Many libraries also accept a key function, which pulls the key out of each record so the library can compare the keys.
Two records can be different and still have equal keys. If you sort ("alice", 3) and ("carol", 3) by score, the comparator calls them equal. The output can therefore place either one first and still count as sorted.
What Makes a Sort Stable
A sort is stable if elements with equal keys come out in the same relative order they had in the input. An unstable sort may swap them.
records = [("alice", 3), ("bob", 1), ("carol", 3), ("dave", 2)]
by_score = sorted(records, key=lambda r: r[1])
print(by_score)
# [('bob', 1), ('dave', 2), ('alice', 3), ('carol', 3)]Python guarantees that sorted is stable. Alice was ahead of Carol in the input, so she stays ahead in the output.
When Stability Changes the Result
Stability is invisible when equal keys mean identical elements, as with a plain list of integers. It matters when records carry data that the key ignores. Say a list is already ordered by signup time and you sort it by country. A stable sort keeps each country's users in signup order. An unstable sort can scramble them, and the result may differ between runs or library versions.
Exercise
The input [("x", 2), ("y", 1), ("z", 2)] is sorted by the number and produces [("y", 1), ("z", 2), ("x", 2)]. Is this output correctly sorted? Could a stable sort have produced it?
Show answer
It is correctly sorted, because the keys read 1, 2, 2. A stable sort could not have produced it, because x came before z in the input and both have key 2, so a stable sort would keep x ahead of z.