What sorting costs, and what "stable" means
1 Sorting a pile of answer sheets
A teacher has marked five answer sheets out of 10. The pile is in roll order, which here is alphabetical. She wants it in order of marks, lowest first, to see who needs help.
Every language has a sort that does this in one line. Writing one by hand still teaches two things:
- Cost. The simple ways to sort take about n² steps. Seeing why tells us when they are fast enough and when they get TLE.
- Ties. Ben and Dev both have 6. Some sorts keep Ben before Dev, as the pile had them, and some do not. That decides which library sort to call.
We sort this pile three ways and watch what each does to Ben and Dev. Each way sorts the array nums = [7, 6, 2, 6, 4] in place, moving values around inside it.
2 Selection sort: pick the smallest of the rest
Selection sort does what most people try first. It finds the lowest sheet and puts it at the front. Then it finds the lowest of the rest and puts it second, and so on.
Each round is a pass. The pass for index i looks at every value from i on and keeps the index of the smallest in min. Then it swaps that value into index i: the two values trade places.
The shaded part never changes again. That is the rule selection sort keeps:
After n − 1 passes, only the largest value is left, and it is already last. In pseudocode:
for i from 0 to n − 2:
min = i
for j from i + 1 to n − 1:
if nums[j] < nums[min]:
min = j
swap nums[i] and nums[min]
3 Bubble sort: swap neighbours
Bubble sort only ever compares neighbours. A pass walks from left to right. When a value is larger than its right neighbour, the two swap. The largest value wins every comparison it meets, so the pass carries it to the end, like a bubble rising. last marks the last index the pass reaches.
Here the finished part grows from the right:
Pass 4 swaps nothing. A pass with no swap means every value is at most its neighbour, so the array is sorted. A flag swapped notices this and stops the passes. On an array that is already sorted, this happens after the first pass.
for last from n − 1 down to 1:
swapped = false
for j from 0 to last − 1:
if nums[j] > nums[j + 1]:
swap nums[j] and nums[j + 1]
swapped = true
if not swapped:
stop
4 Insertion sort: slide each one into place
Insertion sort is how most people sort a pile by hand. They pick up one sheet at a time and slide it left, past the sheets with higher marks, into its place among the ones already in hand.
In code, step i saves nums[i] as key. That leaves a gap at index i, and j marks the gap. While the value just left of the gap is larger than key, it shifts one place right, and the gap moves one place left. Then key drops into the gap.
The tinted part is sorted, but it is not final. After step 3 the two 6s sit at indexes 1 and 2, and the 4 still has to go in front of them. So insertion sort keeps a weaker rule than selection sort:
| i | key | shifted right | j at the end | nums after |
|---|---|---|---|---|
| 1 | 6 | 7 | 0 | [6, 7, 2, 6, 4] |
| 2 | 2 | 7, 6 | 0 | [2, 6, 7, 6, 4] |
| 3 | 6 | 7 | 2 | [2, 6, 6, 7, 4] |
| 4 | 4 | 7, 6, 6 | 1 | [2, 4, 6, 6, 7] |
Every tab turns [7, 6, 2, 6, 4] into [2, 4, 6, 6, 7]. The loop tests j > 0 before it reads nums[j - 1], so it never reads before the front of the array.
5 What the simple sorts cost
Selection sort's passes on our five sheets looked at 4, 3, 2 and 1 values after index i. For n values, they look at n − 1, then n − 2, down to 1. That is about half of n × n, so O(n²). Bubble and insertion sort do as much work on an array in reverse order. All three sort in place, so they need O(1) extra space.
| Sort | Worst case | Already sorted | Moves |
|---|---|---|---|
| Selection | O(n²) | O(n²), it still scans the rest | at most n − 1 swaps |
| Bubble | O(n²) | O(n), one pass with no swap | O(n²) swaps |
| Insertion | O(n²) | O(n), each key stops at once | O(n²) shifts |
Insertion sort's work matches how far values are from home. In the trace table, step 4's key had three larger values before it, so it shifted three times. On a nearly sorted array, each key shifts only a few times, so the whole sort is close to O(n).
At n = 10⁵, n² is 10¹⁰ steps. At about 10⁸ steps a second, that is far past the time limit, so it gets TLE. The library sort takes about n log n steps, around 2 × 10⁶, well under a second.
No sort that only compares two values at a time can beat about n log n comparisons in the worst case. The next lesson reaches that with merge sort and quick sort. A later lesson on counting sort gets under it by not comparing at all.
6 Stable sorts keep ties in order
All three sorts put the marks in the same order. The names under the two 6s tell them apart:
A sort is stable when equal values keep the order they had before the sort. Bubble and insertion sort are stable. Selection sort is not.
Selection sort broke the tie in pass 2. Its swap sent Ben's 6 from index 1 to the far end, past Dev's 6. Bubble and insertion sort move a value one place at a time, and only past a strictly larger value. So a value never passes an equal one.
This needs the strict test. With >= in place of >, insertion sort's step 3 shifts Ben's 6 too, and Dev ends up first.
Stability does not matter for plain numbers, because one 6 looks like another. It matters when values carry more, like a name. The pile was in roll order, so a stable sort by marks keeps ties in roll order for free.
Library sorts differ. The note below follows the language picked in the code tabs:
C++
sort is not stable. stable_sort is, and it takes the same arguments.
Sorting objects is stable. Arrays.sort on objects, Collections.sort and List.sort keep ties in order. Arrays.sort on an int[] is not stable, but equal ints cannot be told apart, so it never matters.
Stable. sort and sorted always keep ties in order.
Stable. The language has required Array.prototype.sort to keep ties in order since 2019.
slices.Sort, slices.SortFunc and sort.Slice are not stable. slices.SortStableFunc and sort.SliceStable are.
sort and sort_by are stable. sort_unstable and sort_unstable_by are not, and they are a little faster.
Array.Sort and List.Sort are not stable. LINQ's OrderBy and OrderByDescending are.
7 Sorting by your own rule
Next the teacher wants a rank list: highest marks first, with ties in roll order. Each sheet is now a name with its marks. A stable sort that compares marks only keeps Ben before Dev. With a sort that is not stable, the comparator would also need the tie-break: by marks, then by name.
C++
true means a goes first. Return a.marks > b.marks, never >=. With >=, two equal marks each say "I go first", and sort can read past the end of the array: a Runtime Error. return a - b; is a bug too, because any number other than 0 counts as true.
A sign, from Integer.compare. Negative means a goes first. b.marks() - a.marks() looks the same but overflows near the ends of the int range: comparing 2 × 10⁹ with −2 × 10⁹ by subtraction puts them the wrong way round.
A key, not a comparator. The sort orders the keys, here the marks made negative so the highest comes first. reverse=True on the marks also keeps ties in order.
A sign, and subtraction is safe. Numbers stay exact far past these sizes. With no compare function, sort compares values as text, so [8, 3, 10, 5].sort() gives [10, 3, 5, 8].
A sign, from cmp.Compare. Negative means a goes first. slices.SortFunc takes the same function but is not stable, so Ben and Dev could swap.
An Ordering, from cmp. b.marks.cmp(&a.marks) flips the order, so the highest comes first. A comparison that is not a consistent order can make the sort panic.
A key, through LINQ. List.Sort takes a comparison instead, but it is not stable. In a comparison, use b.Marks.CompareTo(a.Marks). b.Marks - a.Marks overflows near the ends of the int range and puts 2 × 10⁹ and −2 × 10⁹ the wrong way round.
One rule holds in every language. For two equal values, the comparator must say that neither goes first. If it says each goes before the other, the sort can give a wrong order, and in some languages it crashes.
8 When to use which
The problems in this part of the roadmap ask for one of these sorts by name. Write each from the rule in its section, and check that rule after every pass in a dry run.
Two of them ask for bubble sort and insertion sort with recursion. There, one call does one pass or one step, and a call on the rest of the array takes the place of the outer loop.
Outside those problems, the choice is short:
- Up to a few thousand values: any simple sort is fast enough.
- Nearly sorted input: insertion sort, close to O(n).
- Anything bigger: the library sort, O(n log n).
- Ties that must keep their order: a stable sort, or a tie-break in the comparator.
Practice it
- Selection sortMedium
- Bubble sortMedium
- Insertion sortMedium
- Bubble sort with recursionMedium
- Insertion sort with recursionMedium
Finished this lesson?
Mark it read and it is ticked on the roadmap and in the list.