Input Shapes That Matter for Sorting Cost
Sorted, reverse-sorted, and repeated-key inputs can exercise different branches of the same sorting implementation.
- Source
- Anbloq
- Language
- English
- Created
- Updated
- Chapters
- 4
- Reading time
- 1 min
In this article4 chapters
Trace insertion effort
An insertion sort that shifts larger earlier entries performs no shifts on ascending input. On reverse input of length four it shifts one, two, and three entries in the successive insertions. See sorted insertion.
Check duplicate behavior
If equality also triggers shifts, a list of equal keys can move entries and alter their relative order. Introduce record IDs to observe this independently of the sort keys. Stable sorting specifies the tie guarantee.[1]
Choose inputs that exercise different implementation choices
In insertion sort, sorted distinct keys can minimize moves while reversed keys maximize them. For quicksort that always selects the first key as pivot on sorted distinct input, partitions can have sizes zero and \(n-1\). These arise from different mechanisms. See best and worst cases.
First-pivot quicksort, sorted five keys
Pivot 1 → right size 4
Pivot 2 → right size 3
Pivot 3 → right size 2
Pivot 4 → right size 1
Include ties and nearly sorted input in benchmarks
Equal keys can exercise a partition implementation very differently from reversed distinct keys. A three-way partition may group them in one step. State which pivot selection and tie handling were tested before generalizing a runtime observation.