Data Structures & Algorithms / Module 4: Searching and sorting
Topic 4.6
Sort stability
Whether items with equal values keep their original order, and why that matters for tables and pagination.
Watch: look at the people with equal scores. The first method keeps their original order; the second scrambles it.
- moving now
- passed / marked
- finished / the result
Why it matters
Picture an orders table in an admin app. The user clicks the "date" column, then the "status" column. They expect orders grouped by status, and within each status still in date order. That only happens if the second sort is stable. If not, the date order within each status gets scrambled, and the user thinks data has gone missing.
Which sorts are stable
| Stable | Not stable |
|---|---|
| insertion sort, bubble sort, merge sort, TimSort | selection sort, quick sort, heap sort |
The pattern: sorts that only swap neighbours, or that take the left side on a tie (<= in merge), are stable. Sorts that swap items from far away, like selection sort, can throw an item past others with the same value.
Code, for programmersSorting by two columns
// Since ES2019, Array.prototype.sort is guaranteed to be stable.
orders.sort((a, b) => a.date.localeCompare(b.date)); // first by date
orders.sort((a, b) => a.status.localeCompare(b.status)); // then by status:
// within each status, orders stay in date order
// Or do it in one pass with a tie-breaker:
orders.sort((a, b) =>
a.status.localeCompare(b.status) || a.date.localeCompare(b.date));Quiz
What does a stable sort mean?
Which one is not stable?
A query with ORDER BY status LIMIT 20 OFFSET 20 sometimes repeats rows from page one. The fix?
0 of 3 answered.
Built on
Used in
No follow-up topics yet.