DSA · Patterns, not puzzles
How do common sorting algorithms compare?
Short answer
Comparison sorts are O(n log n) on average, but differ in worst case, stability, memory and adaptivity. Merge sort is stable with O(n) extra space, quicksort is in-place but worst-case O(n^2), and insertion sort is fast on nearly sorted data.
The right sorting algorithm depends on constraints. Do you need stability? Is memory tight? Is the data nearly sorted? Is worst-case latency unacceptable? Interviewers usually want the trade-offs, not a memorised table.
The comparison
- Insertion sort: O(n^2) worst, O(n) on nearly sorted data, stable, in-place
- Merge sort: O(n log n) always, stable, O(n) extra space
- Quicksort: O(n log n) average, O(n^2) worst, in-place, not stable
- Heapsort: O(n log n) always, in-place, not stable
- Counting sort: O(n + k) for a bounded integer range, not comparison-based
const people = [
{ name: "Asha", age: 31 },
{ name: "Ravi", age: 25 },
{ name: "Meera", age: 31 },
];
people.sort((a, b) => a.age - b.age);Stability means equal elements keep their original relative order. That matters when you sort by one field after sorting by another, or when the display order of ties is meaningful. The lower bound for comparison sorting is O(n log n) because there are n! possible orderings.
Follow-ups you should expect
Interviewers use these to check whether the first answer was understanding or memorisation.
- 1Why is comparison sorting bounded by O(n log n)?
- 2When does stability matter?
- 3When would you use counting sort?
- 4Why is quicksort often faster than merge sort in practice?
Say it in the interview
Merge sort gives guaranteed O(n log n) time and stability but needs extra memory. Quicksort is usually faster in practice and sorts in place, but its worst case is quadratic without good pivots. Insertion sort is excellent for small or nearly sorted arrays. I choose based on stability, memory and worst-case requirements, and I remember that comparison sorting cannot beat O(n log n).
Use this as a model, not a script. Saying it in your own words is what makes it survive follow-up pressure.
Related questions
Reading is step one
Now say it out loud.
Understanding an answer and delivering it under pressure are different skills. Rehearse this topic in a live DSA mock interview and get scored feedback on depth, clarity and confidence.