M13 · Sorting

Stability and In-Place Sorting

Two sorts can produce different outputs from the same input and both be correct: they disagree on the order of equal elements. A stable sort keeps that order, which is what lets you sort by several keys in turn. Separately, an in-place sort needs almost no memory beyond the array itself. This lesson defines both properties precisely and classifies the common sorts and the language built-ins.

~30 minIntermediateC# · Python · Java · C++
Curriculum: M13 Sorting · 5 of 5 lessons available

You will be able to

  • Define stability precisely and decide whether a given sort run was stable.
  • Sort records by several keys using successive stable sorts, and explain why the order of the passes matters.
  • Make any sort stable by adding the original index as a tie-breaker.
  • Define in-place sorting by auxiliary space, and classify insertion, selection, bubble, merge, quick, heap and counting sort.
  • Say which built-in sorts in C#, Python, Java and C++ are guaranteed stable.

Helpful before this lesson

  • M03 Big O — Count operations, describe growth, and tell worst-case, average and amortized costs apart.
  • M05 Arrays — Contiguous storage, index arithmetic, and how a dynamic array grows while keeping append cheap.

Guidance only. Those modules are planned; the essentials are recapped here.

Visual walkthrough

The interactive visualizer needs JavaScript. The explanation and all four implementations below work without it.

Mental model

A spreadsheet of orders is sorted by date. You click the "customer" column header to sort by customer. Do each customer's orders stay in date order? If the spreadsheet's sort is stable, yes: orders with the same customer keep the relative order they had before, which was by date. If it is unstable, each customer's orders may come out shuffled, and the earlier sort was wasted.

Stability only matters when elements can compare equal without being identical: two orders with the same customer, two people with the same age, two cards with the same rank. Sorting plain integers, two equal 5s are indistinguishable, so no one can tell whether they swapped.

The lab runs insertion sort. Run the Equal values stay in order preset: the input [5, 2, 5, 1, 2, 5] labels each duplicate with a letter in input order (5a, 5b, 5c), and the sorted output keeps them in that order. Then compare with the selection sort lab, which can carry a later 5 in front of an earlier one with a long-distance swap.

Stability, precisely

A sort is stable if, for every pair of elements x and y that compare equal, x comes before y in the output whenever x came before y in the input.

"Equal" means equal under the comparison used: if you sort people by age, two different people aged 30 are equal for that sort. Stability is a property of the algorithm as implemented. Insertion sort is stable because it stops shifting at an element that is <= the key; change that test to < and the same algorithm becomes unstable. Merge sort is stable because, on a tie, it takes from the left half; take from the right and it is not.

A single run cannot prove a sort stable (it might get lucky), but one counterexample proves it unstable.

Why it matters: sorting by several keys

To sort employees by department, and by salary within each department, there are two methods:

# 1. One sort with a combined comparison (any sort algorithm works)
sort by (department, salary)

# 2. Successive stable sorts, least significant key FIRST
stable sort by salary
stable sort by department

Method 2 works because the second sort groups by department and, being stable, keeps each group in the salary order produced by the first. Doing the passes in the other order sorts by salary in the end and loses the department grouping. Method 1 is usually simpler in code:

Language Combined key Stable built-in for successive passes
C# OrderBy(e => e.Dept).ThenBy(e => e.Salary) Enumerable.OrderBy is stable; Array.Sort and List<T>.Sort are not
Python sorted(staff, key=lambda e: (e.dept, e.salary)) list.sort and sorted are guaranteed stable
Java list.sort(Comparator.comparing(Employee::dept).thenComparing(Employee::salary)) List.sort, Collections.sort, Arrays.sort(Object[]) are guaranteed stable
C++ std::sort with a comparator comparing std::tie(a.dept, a.salary) < std::tie(b.dept, b.salary) std::stable_sort; std::sort is not stable

The successive-pass method is how radix sort works (least significant digit first, each pass a stable counting sort) and how many UIs implement "sort by this column, then that one".

Making any sort stable

Attach each element's original index and use it as the last tie-breaker:

decorated = [(key(x), i, x) for i, x in enumerate(a)]
sort decorated by (key, i)            # no two entries compare equal any more
result = [x for (_, _, x) in decorated]

Now no two entries are equal, so stability is irrelevant and any sort, even an unstable one, produces the stable order. The cost is O(n) extra space for the indices. This is a standard workaround for .NET's unstable Array.Sort.

In place, precisely

A sort is in place if it needs only a small amount of memory beyond the input array. The usual definitions:

  • Strict: O(1) auxiliary space, a few variables. Insertion, selection, bubble and heap sort.
  • Common: O(log n) auxiliary space is also accepted, which admits quicksort, whose recursion uses an O(log n) stack when it recurses on the smaller partition first.

Merge sort on arrays is not in place: the standard merge needs an O(n) buffer, which the merge sort lab shows as a second row. In-place merging algorithms exist but are complicated and slower in practice. On linked lists, merge sort needs no buffer, because merging relinks nodes instead of copying them.

In place is about memory, not about whether elements move: an in-place sort moves elements around inside the array. And "not in place" is not automatically bad: Timsort and std::stable_sort spend up to O(n) memory precisely to be stable and fast.

The classic sorts, classified

Algorithm Stable Auxiliary space Time (worst)
Bubble sort yes O(1) O(n²)
Insertion sort yes O(1) O(n²), O(n) on sorted input
Selection sort no (long-distance swaps) O(1) O(n²)
Merge sort (arrays) yes O(n) O(n log n)
Quicksort no (partitioning swaps across the range) O(log n) stack, O(n) if unbalanced and naively recursive O(n²), O(n log n) expected
Heap sort no (sift-down reorders equals) O(1) O(n log n)
Counting sort yes, as usually written (fill output from the end) O(n + k) for keys in 0 … k O(n + k)
Radix sort (LSD) yes (needs stable digit passes) O(n + base) O(d · (n + base))

The quadratic sorts have their own lesson, and quicksort and heap sort explain where their instability comes from. No comparison sort is known that is stable, strictly in place and O(n log n) worst case and simple: practical libraries pick two of the three (Timsort: stable and O(n log n), up to O(n) memory; introsort: in place and O(n log n), unstable).

To compare the work two stable in-place sorts do on the same array, open bubble sort vs insertion sort.

The built-ins

Call Stable? Notes
C# Array.Sort, List<T>.Sort, Span<T>.Sort no (documented) introsort, in place
C# Enumerable.OrderBy / ThenBy yes (documented) returns a new sequence, O(n) extra
Python list.sort(), sorted() yes (guaranteed by the language docs)
Java Arrays.sort(Object[]), List.sort, Collections.sort yes (guaranteed)
Java Arrays.sort(int[]) and other primitives not specified stability is unobservable for primitives
C++ std::sort no
C++ std::stable_sort, std::ranges::stable_sort yes
C++ std::partial_sort, std::nth_element no

The built-in sorts lesson explains the algorithms behind these calls.

The teaching implementation

The four listings below are insertion sort from the elementary sorts lesson; the lab highlights the comparison line whenever it compares the key with the element to its left. That line is the one that decides stability: it shifts an element only while it is strictly greater than the key, so an equal element is never jumped over. The listings are checked against the merge sort fixture, which verifies stability, and against each language's stable built-in sort on random inputs.

Common mistakes

  • Assuming Array.Sort or std::sort is stable because it happened to keep the order in a small test.
  • Running successive stable sorts in the wrong order: the primary key must be sorted last.
  • Calling merge sort in place on arrays.
  • Breaking stability by accident: < instead of <= in a merge's tie rule, or >= instead of > in insertion sort's shift condition.
  • Comparators that are not consistent (for example, returning "less" for both a, b and b, a): then no sort, stable or not, has a well-defined result, and Java's TimSort may throw IllegalArgumentException: Comparison method violates its general contract.

Edge cases

  • All elements distinct under the comparison: every correct sort gives the same output, so stability cannot be observed.
  • All elements equal: a stable sort returns the input unchanged.
  • Sorting by a key that maps many elements to the same value (e.g. len): stability decides the order within each group.

Worked practice

1. Sort the cards [7♠, 3♥, 7♥, 3♠, 5♦] by rank with a stable sort. Then with selection sort (select the minimum, swap it to the front). Are the results the same?

Answer

Stable: [3♥, 3♠, 5♦, 7♠, 7♥]. Selection sort: swap 3♥ with 7♠ → [3♥, 7♠, 7♥, 3♠, 5♦]; the minimum of the rest is 3♠ at index 3, swap with 7♠ → [3♥, 3♠, 7♥, 7♠, 5♦]; then 5♦ swaps with 7♥ → [3♥, 3♠, 5♦, 7♠, 7♥]. Here the result happens to match, because the second swap put 7♠ back in front. Try [5♠, 5♥, 3♦]: the first swap gives [3♦, 5♥, 5♠], an unstable result.

2. You need students ordered by grade (descending), and alphabetically by name within each grade, using only stable sorts. In which order do you sort?

Answer

First by name (ascending), then by grade (descending). The last pass is the primary key.

3. Is heap sort in place? Is it stable?

Answer

In place (O(1) extra: the heap lives in the array itself), but not stable: sifting moves elements across long distances and can reorder equal keys.

4. Why is merge sort on a linked list in place, but not on an array?

Answer

Merging two lists only relinks next pointers; no element is copied, so no buffer is needed (only the O(log n) recursion stack, or O(1) bottom-up). Merging two array halves needs somewhere to put elements while both halves are still being read.

Summary

  • Stable: equal elements keep their input order. It matters only when equal elements are distinguishable.
  • Successive stable sorts, least significant key first, give a multi-key order; a combined comparison does it in one pass.
  • Any sort becomes stable with the original index as a tie-breaker.
  • In place: O(1) (strictly) or O(log n) extra space. Merge sort on arrays is not in place.
  • Guaranteed stable: Python's sort, Java's object sorts, C#'s OrderBy, C++'s std::stable_sort. Not stable: C#'s Array.Sort, C++'s std::sort.

Full implementation

Insertion sort in four languages, checked against the merge sort fixture (which also verifies stability) and random inputs compared with the language's stable built-in sort.

namespace Bekadan.Dsa.Examples.Sorting;
 
/// <summary>
/// Bubble sort (with the early exit) and insertion sort. Both are stable and in
/// place: Θ(n²) comparisons in the worst case, Θ(n) on already sorted input.
/// </summary>
public static class ElementarySorts
{
    public static void BubbleSort<T>(T[] items, Comparison<T> compare)
    {
        for (int end = items.Length - 1; end > 0; end--)
        {
            bool swapped = false;
            for (int i = 0; i < end; i++)
            {
                if (compare(items[i + 1], items[i]) < 0) // strictly smaller: equal items never swap (stable)
                {
                    (items[i], items[i + 1]) = (items[i + 1], items[i]);
                    swapped = true;
                }
            }
            if (!swapped)
                break; // no swap in a whole pass: already sorted
        }
    }
 
    public static void InsertionSort<T>(T[] items, Comparison<T> compare)
    {
        for (int i = 1; i < items.Length; i++)
        {
            T key = items[i];
            int j = i - 1;
            while (j >= 0 && compare(items[j], key) > 0) // strictly greater: equal items stay in order (stable)
            {
                items[j + 1] = items[j];
                j--;
            }
            items[j + 1] = key;
        }
    }
}

Tested on .NET 10 (SDK 10.0.403), C# 14 · examples/csharp/Bekadan.Dsa.Examples/Sorting/ElementarySorts.cs

"""Bubble sort (with the early exit) and insertion sort.
 
Both are stable and in place: Θ(n²) comparisons in the worst case, Θ(n) on
already sorted input.
"""
 
from collections.abc import Callable
from typing import Any
 
 
def _identity(item: Any) -> Any:
    return item
 
 
def bubble_sort(items: list[Any], key: Callable[[Any], Any] = _identity) -> None:
    for end in range(len(items) - 1, 0, -1):
        swapped = False
        for i in range(end):
            if key(items[i + 1]) < key(items[i]):  # strictly smaller: equal items never swap (stable)
                items[i], items[i + 1] = items[i + 1], items[i]
                swapped = True
        if not swapped:
            break  # no swap in a whole pass: already sorted
 
 
def insertion_sort(items: list[Any], key: Callable[[Any], Any] = _identity) -> None:
    for i in range(1, len(items)):
        current = items[i]
        j = i - 1
        while j >= 0 and key(items[j]) > key(current):  # strictly greater: equal items stay in order (stable)
            items[j + 1] = items[j]
            j -= 1
        items[j + 1] = current

Tested on CPython 3.14.0 · examples/python/dsa_examples/elementary_sorts.py

package dev.bekadan.dsa.sorting;
 
import java.util.Comparator;
 
/**
 * Bubble sort (with the early exit) and insertion sort. Both are stable and in
 * place: Θ(n²) comparisons in the worst case, Θ(n) on already sorted input.
 */
public final class ElementarySorts {
    private ElementarySorts() {
    }
 
    public static <T> void bubbleSort(T[] items, Comparator<? super T> comparator) {
        for (int end = items.length - 1; end > 0; end--) {
            boolean swapped = false;
            for (int i = 0; i < end; i++) {
                if (comparator.compare(items[i + 1], items[i]) < 0) { // strictly smaller: equal items never swap (stable)
                    T tmp = items[i];
                    items[i] = items[i + 1];
                    items[i + 1] = tmp;
                    swapped = true;
                }
            }
            if (!swapped) {
                break; // no swap in a whole pass: already sorted
            }
        }
    }
 
    public static <T> void insertionSort(T[] items, Comparator<? super T> comparator) {
        for (int i = 1; i < items.length; i++) {
            T key = items[i];
            int j = i - 1;
            while (j >= 0 && comparator.compare(items[j], key) > 0) { // strictly greater: equal items stay in order
                items[j + 1] = items[j];
                j--;
            }
            items[j + 1] = key;
        }
    }
}

Tested on Java 25 (Temurin 25.0.5); also compiles on Java 17 · examples/java/src/main/java/dev/bekadan/dsa/sorting/ElementarySorts.java

#pragma once
 
#include <cstddef>
#include <functional>
#include <span>
#include <utility>
 
namespace bekadan::dsa {
 
// Bubble sort (with the early exit) and insertion sort. Both are stable and in
// place: Θ(n²) comparisons in the worst case, Θ(n) on already sorted input.
 
template <typename T, typename Less = std::less<>>
void bubble_sort(std::span<T> items, Less less = {}) {
    for (std::size_t end = items.size(); end > 1; --end) {
        bool swapped = false;
        for (std::size_t i = 0; i + 1 < end; ++i) {
            if (less(items[i + 1], items[i])) {  // strictly smaller: equal items never swap (stable)
                std::swap(items[i], items[i + 1]);
                swapped = true;
            }
        }
        if (!swapped)
            break;  // no swap in a whole pass: already sorted
    }
}
 
template <typename T, typename Less = std::less<>>
void insertion_sort(std::span<T> items, Less less = {}) {
    for (std::size_t i = 1; i < items.size(); ++i) {
        T key = std::move(items[i]);
        std::size_t j = i;  // the gap is at j; compare with items[j - 1]
        while (j > 0 && less(key, items[j - 1])) {  // strictly greater on the left: equal items stay in order
            items[j] = std::move(items[j - 1]);
            --j;
        }
        items[j] = std::move(key);
    }
}
 
}  // namespace bekadan::dsa

Tested on C++23, GCC 15.3 (libstdc++) · examples/cpp/include/bekadan/dsa/elementary_sorts.hpp

References