Two lists can be sorted the same way by value and still disagree on who stands next to whom. The difference is stability — and it is decided in the tie case.
All records sharing one key. Stability has nothing to say about records with different keys — only about who keeps their place inside a group of equals.
Merge sort is stable only if its tie case takes the left item first. Insertion sort stays stable if it never moves an item past an equal key. Quicksort/heap need extra machinery.
To order by state then city, sort by the secondary key (city) first, then the primary key (state). The final stable pass preserves city order inside each state.
Tag each record with its unique input index, create repeated keys, sort, then compare index order inside each tie group. Any reversal proves the sort is not stable.
Start with tied keys. Here B and D both carry 35, so any sort by age must decide their relative order.
B remains before D because their keys tie and the input had B first. An unstable sort might emit D before B — still sorted, still “correct” — and downstream code that assumed input order silently breaks.
Stack keys in reverse. For “state, then city” the execution order is the reverse of the reading order: stable sort by city first, then stable sort by state.
The last pass wins. Each stable pass fixes the order of ties on its own key, and a later stable pass leaves those resolved ties untouched — so city order survives inside every state group.