Stability

Beginner Algorithms and Data Structures English
Also available: Deutsch
Created by Best · 16.08.2026 at 09:13 UTC

A sorter is stable if equal keys maintain their relative order. Insertion Sort is stable; Selection Sort is typically not (depending on the implementation).

Stability matters when additional data is attached to keys.

Where used

Multilevel sorting (first by name, then by grade) and UI tables: stable sorting preserves the previous order. Collections.sort / TimSort are stable; classic Quicksort is typically not.

Depth

A sort is stable if records with the same sort key appear in the same mutual sequence afterward as they did before. This is relevant when multiple sorting steps are combined, such as sorting by first name and then by last name.

Stability is a property of the concrete implementation, not just the algorithm name. Insertion Sort can be stable by only moving strictly larger elements. In contrast, Selection Sort with a wide swap can move an equivalent record over another.

Difficulty levels

  1. Check stability on records with a key and additional identifier.
  2. Make a comparison condition stable or unstable.
  3. Plan multilevel sorts in the correct order.

Pitfalls

Stability cannot be observed with arrays containing entirely different values. A check requires equal keys with distinguishable accompanying data; otherwise, a loss of order remains invisible.

University approvals: 0
Tasks
Question 1

What does stable sorting mean?

Question 2

Records were first sorted by first name and then stably by last name. What applies within a last name?

Question 3

Sort the pair objects stably by key. For equal keys, the original order of the ids must be preserved.

Hint

Arrays.sort(T[], Comparator) sorts object arrays in a stable manner. A Comparator can be created using Comparator.comparingInt(p -> p.key).

Starter code is prefilled; replace TODO blocks with your solution.
1 test case will be used for grading
Run checks runtime behavior only. Final correctness is evaluated when you submit.
Card Info
  • Topic: Algorithms and Data Structures
  • Difficulty: Beginner
  • Completed: 0 users
Creator
Best
Best
BestBuddy