Interview Q&A / Data Structures & Algorithms

IntermediateQuick answerCoding1 min readUpdated 3 Oct 2026

What is a stable sort and why does it matter?

SHORT ANSWER

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

js
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.

#sorting#javascript

Related questions

Practise more Data Structures & Algorithms questions

Test your recall with short answers, then return to the detailed explanations when you need context.

Open Data Structures & Algorithms quick answers →

Get new questions like this by email

One short email when something new and useful lands. No spam, unsubscribe in one tap.

By subscribing you agree to the Privacy Policy.