Choosing a sort comes down to a few properties: time complexity, stability, in-place memory use, and the nature of the data. No single sort wins everywhere.
Choosing a sort comes down to a few properties: time complexity, stability, in-place memory use, and the nature of the data. No single sort wins everywhere.
| Algorithm | Avg time | Worst | Stable | In-place |
|---|---|---|---|---|
| Insertion | O(n²) | O(n²) | Yes | Yes |
| Merge | O(n log n) | O(n log n) | Yes | No |
| Quick | O(n log n) | O(n²) | No | Yes |
| Heap | O(n log n) | O(n log n) | No | Yes |
# Most languages ship a tuned hybrid; prefer it in production
sorted(data, key=lambda x: x.priority) # stable Timsort in Python
Don't hand-roll a sort unless you have a specific reason — library sorts (Timsort, introsort) are battle-tested hybrids.
Matching the sort to the data and requirements avoids both wasted time and subtle bugs (like losing stability).
Understanding the trade-offs explains why standard libraries chose hybrids like Timsort and introsort.
This comparative judgment — not memorizing one algorithm — is what real engineering and interviews reward.
A library of IT interview questions with detailed answers — from Junior to Senior.
Donate