Stable Ordering of Equal-Key Items
A stable sort keeps the relative order of inputs whose sort keys compare equal.
- Source
- Anbloq
- Language
- English
- Created
- Updated
- Chapters
- 4
- Reading time
- 1 min
In this article4 chapters
Use two visible records
Given Bea with score 5, Ali with score 3, and Cy with score 5, an ascending stable sort by score yields Ali, Bea, Cy. The order of Bea and Cy still conveys their input order. A postcondition can make that tie behavior explicit.
Build a tie test
A test containing only distinct keys cannot distinguish stable and unstable output. Label two equal-score records with different identifiers and assert the label order. Key-based sorting explains how choosing a key defines which items tie.[1]
Label duplicates so their order can be inspected
Suppose requests arrive as (2, A), (1, B), (2, C) and (1, D). A stable sort by priority produces B, D, A, C. A test comparing only [1, 1, 2, 2] cannot tell whether order among ties survived. Test request identities in the output. If equal-priority arrivals need chronological order, feed the sort a sequence that already carries the relevant chronology. See sequences of events.
Layer stable sorts in the correct direction
To order by priority and then by label using two stable passes, first sort by the secondary label, then by the primary priority. The second pass preserves label order in each equal-priority run. Reversing these passes makes label the primary key. A tuple key can express both fields in one call when their comparison directions are compatible. See key functions for sorting.