Boss lesson · Unit 02
Stable or not
Keep ties in order, then sort by two keys
What you practise
- What stability means, which simple sorts have it, sorting by two keys
Try a question from this lesson
Pick one
Orders arrive in this order: Ann $5, Bo $3, Cy $5, Di $3. You sort by price, cheapest first. Which result keeps equal prices in arrival order?
Correct answer
Bo, Di, Ann, Cy
Why
Bo arrived before Di and Ann before Cy, and only the first option keeps both pairs that way round. All four options are sorted by price; a sort that also keeps ties in order is called stable.
The ideas
Concept cards are short on purpose. In the app they appear between questions, after you have met the idea.
Concept
Stable sorts
A sort is stable if items with equal keys come out in the same order they went in.
It does not matter for plain numbers: one 5 is as good as another. It matters when the items are records and you sort by one field: a spreadsheet sorted by date, then by customer, should still be in date order within each customer.
Concept
Why selection sort is unstable
Bubble sort and insertion sort only move an item past a neighbour that is strictly bigger, so equal items never overtake each other.
Selection sort swaps across a distance. Sorting 5a, 5b, 3 it swaps the 3 with 5a, giving 3, 5b, 5a: the first 5 was thrown behind its twin.
10 more exercises in the app
- 6× multiple choice
- 1× true or false
- 1× match the pairs
- 1× order the lines
- 1× fill the blanks
Bitpath is an iOS app in development. Join the waitlist and you get one email when it is ready to try.