Video in progress

Strong Junior 🧠 Problem solving

What is a stable sort, and when does it change the result?

A stable sort preserves the original relative order of elements with equal keys. The difference shows up when you sort by several fields in stages, or when the earlier order has meaning.

📖 Answer

Say orders arrived in time order:

(10:00, Ali, NEW) (10:05, Vali, PAID) (10:07, Sami, NEW)

We sort by status. A stable sort keeps Ali before Sami among the NEW ones, because he came first. An unstable sort may swap them, and the user complains that "the queue got messed up".

In Java:

  • List.sort, Collections.sort, Arrays.sort(Object[]), stream().sorted() are stable (TimSort);
  • Arrays.sort(int[]) is not stable, but that doesn't matter for primitives.

By algorithm: merge sort, insertion sort and TimSort are stable; quicksort, heap sort and selection sort usually aren't.

One catch: relying on stability to sort twice, "second key first, then the first key", works, but it's confusing for whoever reads the code. Writing a single Comparator.comparing(...).thenComparing(...) is clearer.