Stability in Sorting Algorithms
A sorting algorithm is considered stable if it preserves the relative order of elements that compare as equal according to the sort key. That is, if two elements have the same value, a stable sort guarantees they will appear in the output in the same relative order as they appeared in the input.
Stability matters when sorting complex objects by one attribute while wanting to preserve a previously established order on another attribute. A common real-world example is sorting a list of employees by department after they have already been sorted by name — a stable sort ensures that employees within the same department remain sorted alphabetically by name after the department sort.
Stable sorting algorithms: Merge Sort, Insertion Sort, Bubble Sort, Timsort
Unstable sorting algorithms: Quick Sort (typical implementation), Heap Sort, Selection Sort
Stability is essential for multi-key sorting (sort by key A, then stably by key B)
Some unstable algorithms can be made stable by adding index-based tie-breaking, at the cost of extra memory
0-2 years experience
2-5 years experience
5-8 years experience
8+ years experience