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.

7 min · intermediate

Watch: look at the people with equal scores. The first method keeps their original order; the second scrambles it.

was #1was #2was #3was #4was #53 Ana1 Budi2 Cici3 Dedi1 Eko
  • moving now
  • passed / marked
  • finished / the result
Step 1 of 6

Sort by score. People are already in name order; watch what happens to equal scores.

A stable sort never swaps two items it considers equal. That matters when you sort in stages: by name first, then by score.

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

StableNot stable
insertion sort, bubble sort, merge sort, TimSortselection 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

  1. What does a stable sort mean?

  2. Which one is not stable?

  3. A query with ORDER BY status LIMIT 20 OFFSET 20 sometimes repeats rows from page one. The fix?

0 of 3 answered.