Skip to content
IT glossary
AlgorithmsUpdated December 3, 2026

Stable sorting

Устойчивость сортировки

A sort is stable if items with the same sort key stay in the same relative order as they were in the input.

What a stable sort preserves

Suppose a support queue is already in arrival order. If you sort it by priority using a stable sort, earlier tickets still come before later tickets of the same priority. A ticket can move to a different position in the list. The guarantee is about which ticket comes first when the two tie, not about either ticket's position.

A tie is defined by the sort key or comparator. Two tickets can have different IDs and descriptions but still tie when you compare only their priorities. An unstable sort can put every ticket in the correct priority group without preserving arrival order within those groups. It might preserve that order on some inputs; it just doesn't guarantee it.

Where the guarantee comes from

Consider merge sort on an array. Splitting the array into contiguous halves puts every element from the left half earlier in the input than every element from the right half. When merging the sorted halves, take the left element first if the two candidates tie. Apply that rule at every merge and the original order of tied elements is preserved. Taking the right element first on a tie can reverse that order. Standard in-place versions of quicksort and heapsort, by contrast, can reorder tied elements through swaps. Check the guarantee of the specific implementation or API rather than assuming stability from its name.

Example: sort one field at a time

To order orders by destination, then by shipping cost within each destination, sort by cost first and destination last. Python's list.sort() is stable, so the last pass keeps the cost order inside each destination group.

# (order ID, destination, shipping cost)
orders = [('A', 'NY', 8), ('B', 'CA', 12), ('C', 'CA', 5)]
orders.sort(key=lambda order: order[2])  # C, A, B
orders.sort(key=lambda order: order[1])  # C, B, A

The destination pass groups C and B together without moving the more expensive order ahead of the cheaper one. If both keys are available at once, sorting by (order[1], order[2]) expresses the same precedence in a single call.

Common pitfalls and interview questions

Stability is useful when someone sorts a table by a new column and expects the previous ordering to break ties. It does not make ties independent of the input order. If a report needs the same row order regardless of how records were loaded, specify an explicit tie-breaker such as a unique record ID.

In an interview, use labeled records to demonstrate instability. For (2, A), (2, B), (1, C), ask the implementation to sort only by the number. A sorted output with B before A disproves stability. An output with A before B only shows that this input passed. To establish the guarantee, explain why the implementation cannot reverse any pair that compares equal.