What is a stable sort and why does it matter?
A stable sort keeps items with equal keys in their original relative order. It matters when you sort by one field after another, such as by marks first and then keep the earlier name order for ties.
Explain it simply
Suppose a result list is already sorted by name: Asha, Neha, Ravi. Now you sort by marks. Asha and Neha both scored 80. A stable sort keeps Asha before Neha because that was their order before. An unstable sort may swap them.
This is why multi-level sorting works: sort by the least important field first, then by the most important using a stable sort. Merge sort and insertion sort are stable; quick sort and heap sort usually are not. Since ES2019, JavaScript requires Array.prototype.sort to be stable.
Example
const students = [
{ name: "Asha", marks: 80 },
{ name: "Neha", marks: 80 },
{ name: "Ravi", marks: 90 },
];
students.sort((a, b) => b.marks - a.marks);
console.log(students.map((s) => s.name)); // Output: ["Ravi","Asha","Neha"]Complexity
Stability does not change time complexity: merge sort stays O(n log n).
What to say in the interview
"A stable sort preserves the original order of equal elements. It lets me sort by several keys in passes, and keeps results predictable for ties. Merge sort is stable, quick sort typically is not, and modern JavaScript guarantees a stable Array sort."
Common mistakes
- Believing every O(n log n) sort is stable.
- Ignoring stability when sorting records by a secondary field.