Fundamentals · Medium · Free
What is a stable sort? Which common sorts are stable?
FresherFundamentalsData Structures & Algorithms
Stable sorting
A sort is stable if equal keys retain original relative order. Matters when sorting by one key then another (sort by name after sorting by department).
- Stable: merge sort, insertion sort, bubble sort, TimSort.
- Unstable: quick sort, heap sort (typical implementations).
java
// Java Collections.sort on objects is stable (TimSort)
students.sort(Comparator.comparing(Student::getGrade)
.thenComparing(Student::getName));Example: sort students by grade, then by name—stability preserves grade groups.