M13 · Sorting

What Built-in Sorts Actually Do

No standard library ships the textbook merge sort or quicksort. They ship hybrids: merge sorts that find existing order and switch to insertion sort on short runs, and quicksorts that fall back to heap sort before they can go quadratic. This lesson explains what the sort call in C#, Python, Java and C++ actually runs, which properties are guaranteed by the documentation and which are implementation details.

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

You will be able to

  • Name the algorithm behind the default sort in C#, Python, Java and C++ and state which properties are documented guarantees.
  • Explain how Timsort finds natural runs, extends short ones with binary insertion sort, and merges them.
  • Describe galloping and why it makes merging cheap when one run's elements mostly precede the other's.
  • Explain how introsort keeps quicksort's speed while guaranteeing O(n log n), and why small partitions use insertion sort.
  • Choose the right call when you need stability, a partial sort, or a sort that never allocates.

Helpful before this lesson

  • M03 Big O — Count operations, describe growth, and tell worst-case, average and amortized costs apart.

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

Textbook sorts each have a weak spot. Merge sort always does about n log n comparisons, even on an array that is already sorted. Quicksort is fast on average but quadratic on unlucky inputs. Insertion sort is quadratic in general but unbeatable on tiny or nearly sorted arrays.

Library sorts are hybrids that combine the strengths and cover the weak spots:

  • Timsort (Python, Java objects, also Android and V8): a merge sort that first looks for runs that are already sorted, uses insertion sort to build short runs, and merges cleverly.
  • Introsort (.NET, the usual std::sort): a quicksort that watches its own recursion depth and switches to heap sort before it can degrade, with insertion sort for small partitions.
  • Dual-pivot quicksort (Java primitives): quicksort with two pivots and three partitions, plus fallbacks.

The lab on this page is the plain top-down merge sort from the merge sort lesson. Keep it in mind as the baseline the hybrids improve on: run its Already sorted preset and notice that it still splits all the way down and merges every level, which is exactly the waste Timsort avoids. There is no Timsort or introsort code on this page; the descriptions below are conceptual and point to the real sources.

What each language runs

Call Algorithm (current implementation) Stable Worst case Extra memory
C# Array.Sort, List<T>.Sort, Span<T>.Sort introsort (documented) no (documented) O(n log n) O(log n)
C# Enumerable.OrderBy sorts extracted keys, original index as tie-breaker yes O(n log n) O(n)
Python list.sort, sorted Timsort; since 3.11 with the Powersort merge policy yes (guaranteed) O(n log n) up to n/2 references
Java Arrays.sort(Object[]), List.sort, Collections.sort TimSort (documented as an implementation note) yes (guaranteed) O(n log n) up to n/2 references
Java Arrays.sort(int[]) and other primitives dual-pivot quicksort (documented as an implementation note) not applicable O(n log n) (documented) O(log n) typically
C++ std::sort not specified; libstdc++ and libc++ use introsort variants no O(n log n) comparisons (required since C++11) O(log n)
C++ std::stable_sort not specified; typically merge sort with a temporary buffer yes O(n log n) with enough memory, O(n log² n) without O(n) if available

Two kinds of statements are mixed in that table, and the difference matters:

  • Guarantees are in the specification or API contract: Python's and Java's object sorts are stable, .NET's Array.Sort is not, C++ std::sort makes O(n log n) comparisons and std::stable_sort is stable. Code may rely on these.
  • Implementation notes describe the current algorithm: "TimSort", "dual-pivot quicksort", "introsort". Java's documentation explicitly labels these as notes that may change; C++ names no algorithm at all. Do not rely on, say, exact comparison counts.

Timsort, conceptually

Tim Peters designed it for CPython in 2002; his listsort.txt (in the references) is the authoritative description. The ideas, in order:

1. Find natural runs. Scan from the left for a maximal run that is already ascending (a[i] <= a[i+1]) or strictly descending (a[i] > a[i+1]). A strictly descending run is reversed in place; strictness is what keeps the reversal stable, since equal elements are never inside one.

2. Extend short runs with binary insertion sort. If a natural run is shorter than minrun (chosen between 32 and 64 so that n / minrun is close to a power of two), extend it to minrun elements with binary insertion sort: insertion sort that finds the insertion point by binary search. Element moves are still quadratic in the worst case, but on at most 64 elements a move is a short memmove, and comparisons, which can be expensive for Python objects, drop to O(log minrun) each.

3. Merge runs on a stack, keeping them balanced. Each run is pushed onto a stack, and adjacent runs are merged when their lengths would otherwise become unbalanced. Balanced merges keep the total work at O(n log n) and the merge buffer small. The original rules had a subtle bug, found in 2015 by a formal verification effort, that could overflow the run stack on huge crafted inputs; it was fixed in CPython and Java. Since Python 3.11, CPython chooses merges with the Powersort policy (Munro and Wild), which gives provably near-optimal merge trees; the run detection and galloping are unchanged.

4. Merge with galloping. A merge copies the shorter run into a temporary buffer (at most n/2 elements) and merges back into the array. Normally it compares one element from each run at a time. If one run "wins" many times in a row (7 by default, adapted as it goes), the merge switches to galloping: it probes the winning run at offsets 1, 3, 7, 15, … (exponential search) to find how far the other run's next element reaches, then binary-searches inside that span and copies the whole block at once. When one run's elements mostly come before the other's, a block of k elements costs O(log k) comparisons instead of k. Galloping is the same doubling idea as exponential search in the searching module.

Result: O(n) comparisons on already sorted or reversed data, O(n log n) in the worst case, stable, and very few comparisons on real data with partial order (appended records, concatenated sorted lists). The memory cost is the merge buffer, up to n/2 elements.

Introsort, conceptually

David Musser's introsort (1997) starts as quicksort and keeps a depth budget, typically 2 ⌊log₂ n⌋:

introsort(range, depthLimit):
    if size(range) <= 16:         insertion sort; return      # small: low overhead wins
    if depthLimit == 0:           heap sort the range; return # recursion is degenerating
    p = choose pivot (e.g. median of three)
    partition range around p
    introsort(left part,  depthLimit - 1)
    introsort(right part, depthLimit - 1)

Balanced partitions never exhaust the budget, so typical inputs run at quicksort speed. An adversarial or unlucky input that keeps producing lopsided partitions hits the limit, and heap sort finishes that range in O(m log m). The whole sort is therefore O(n log n) worst case and in place, at the price of stability.

.NET's documentation spells out its version: insertion sort for partitions of at most 16 elements, heap sort when the number of partitions exceeds 2 log n, quicksort otherwise. libstdc++'s std::sort stops partitioning ranges below 16 elements and finishes the whole array with one insertion sort pass at the end; libc++ uses a similar introsort with extra tuning. These thresholds are implementation details.

The quicksort lesson and the heap sort lesson cover the two halves of introsort, and insertion sort the third.

Dual-pivot quicksort (Java primitives)

Arrays.sort(int[]) and the other primitive overloads use the dual-pivot quicksort by Vladimir Yaroslavskiy, Jon Bentley and Joshua Bloch, introduced in Java 7. Two pivots p ≤ q split the range into three parts (< p, between, > q), which in practice reduces memory traffic compared with one pivot. The current OpenJDK implementation also falls back to heap sort when recursion gets too deep, uses insertion sort variants for small ranges, merges when it detects runs, and switches to counting sort for byte, short and char arrays above a size threshold. The documentation promises O(n log n) on all data sets.

Why not Timsort for primitives too? Stability is invisible for primitives (two equal ints cannot be told apart; -0.0/0.0 and NaN ordering for floating point are defined by the method), so a faster unstable sort costs nothing. Objects need stability, and comparing them through compareTo is expensive, which favours Timsort's low comparison count.

Choosing the right call

Need C# Python Java C++
Fast general sort Array.Sort, List<T>.Sort list.sort Arrays.sort, List.sort std::sort
Guaranteed stable OrderBy / ThenBy, or decorate with the index list.sort (always stable) List.sort, Arrays.sort(Object[]) std::stable_sort
Only the k smallest, in order PriorityQueue or sort a copy heapq.nsmallest(k, a) PriorityQueue std::partial_sort
The k-th smallest only (none built in) (none built in) (none built in) std::nth_element, average O(n)
No allocation Span<T>.Sort (not guaranteed) primitives: Arrays.sort std::sort
Parallel PLINQ AsParallel().OrderBy (none built in) Arrays.parallelSort std::sort(std::execution::par, …)

Whatever the call, the comparison must be a strict weak ordering: consistent, transitive, and never "less" in both directions. Violating it is undefined behaviour for std::sort (it can read outside the range), may throw "Comparison method violates its general contract" in Java's TimSort, and produces an arbitrary order elsewhere. Subtraction comparators (return a - b) overflow for large ints; use Integer.compare, a.CompareTo(b) or <.

Common mistakes

  • Relying on stability from Array.Sort or std::sort.
  • Calling an implementation note a guarantee, for example "Java's sort is Timsort, so it is O(n) on sorted input" in an interview; the guarantee is O(n log n) and stability.
  • Inconsistent comparators, including ones that use mutable state or random numbers.
  • Sorting to find a minimum or the top k: O(n) and O(n log k) alternatives exist.
  • Re-implementing sorts in production because a textbook sort looks simpler. The built-ins have years of tuning and adversarial testing behind them.

Edge cases

  • Empty and single-element arrays: every built-in returns immediately.
  • Already sorted input: Timsort does n − 1 comparisons; introsort still partitions (fast, but O(n log n)).
  • Reverse-sorted input: Timsort reverses one descending run in O(n); a naive first-element-pivot quicksort would go quadratic, which is why real quicksorts choose pivots carefully and why introsort has its fallback.
  • Many duplicates: three-way partitioning (Java's dual-pivot sort handles equal keys specially) avoids quadratic behaviour on arrays like [5, 5, 5, …].

Worked practice

1. A list of 10,000 log records sorted by time gets 50 new records appended, also in time order but interleaved with the old ones. Why does list.sort() handle this well?

Answer

There are two natural runs: the 10,000 old records and the 50 new ones. Timsort detects both in O(n) and performs one merge. Galloping copies long stretches of old records between consecutive new ones with O(log k) comparisons each, so the total is far below n log n comparisons.

2. Why does introsort switch to heap sort and not to merge sort when the depth limit is reached?

Answer

Heap sort is O(n log n) worst case and in place, so the whole algorithm keeps O(log n) extra space. Merge sort would need an O(n) buffer, and introsort is not stable anyway.

3. You must sort 1 million Person objects by last name, keeping people with the same last name in their current order. Which call do you use in each language?

Answer

C#: people.OrderBy(p => p.LastName) (stable), not List<T>.Sort. Python: people.sort(key=...). Java: people.sort(Comparator.comparing(Person::lastName)). C++: std::stable_sort with a comparator on last_name.

4. Why does Timsort reverse only strictly descending runs, not runs like [5, 4, 4, 3]?

Answer

Reversing [5, 4a, 4b, 3] would give [3, 4b, 4a, 5], swapping the two equal 4s and breaking stability. With strictly descending runs there are no equal elements inside a run to swap.

Summary

  • Built-in sorts are hybrids: Timsort (Python, Java objects) and introsort (.NET, typical std::sort), plus dual-pivot quicksort for Java primitives.
  • Timsort finds natural runs, extends short ones with binary insertion sort, merges a balanced stack of runs (Powersort policy since Python 3.11) and gallops when one run dominates: stable, O(n) on sorted data, O(n log n) worst case, up to n/2 extra.
  • Introsort is quicksort with a depth limit and a heap sort fallback, plus insertion sort for small ranges: in place, O(n log n) worst case, unstable.
  • Rely on documented guarantees (stability, complexity), not on the current algorithm.
  • Use std::stable_sort, OrderBy, or Python's and Java's object sorts when equal elements must keep their order.

Full implementation

The same sort in four languages, each checked against one shared set of test cases that also verify stability, and 500 random inputs compared with the language's stable built-in sort.

namespace Bekadan.Dsa.Examples.Sorting;
 
/// <summary>
/// Top-down merge sort: stable, O(n log n) comparisons in every case,
/// O(n) auxiliary space for one buffer plus O(log n) stack frames.
/// </summary>
public static class MergeSort
{
    public static void Sort<T>(T[] items, Comparison<T> compare)
    {
        var buffer = new T[items.Length];
        SortRange(items, buffer, 0, items.Length, compare);
    }
 
    /// <summary>Sorts items[low..high) (high exclusive).</summary>
    private static void SortRange<T>(T[] items, T[] buffer, int low, int high, Comparison<T> compare)
    {
        if (high - low <= 1)
            return;
        int mid = low + (high - low) / 2;
        SortRange(items, buffer, low, mid, compare);
        SortRange(items, buffer, mid, high, compare);
        Merge(items, buffer, low, mid, high, compare);
    }
 
    /// <summary>Merges the sorted halves items[low..mid) and items[mid..high).</summary>
    private static void Merge<T>(T[] items, T[] buffer, int low, int mid, int high, Comparison<T> compare)
    {
        for (int p = low; p < high; p++)
            buffer[p] = items[p];
        int i = low, j = mid, k = low;
        while (i < mid && j < high)
        {
            if (compare(buffer[i], buffer[j]) <= 0) // <= takes the left one on ties: stable
                items[k++] = buffer[i++];
            else
                items[k++] = buffer[j++];
        }
        while (i < mid)
            items[k++] = buffer[i++];
        while (j < high)
            items[k++] = buffer[j++];
    }
}

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

"""Top-down merge sort.
 
Stable, O(n log n) comparisons in every case, O(n) auxiliary space for one
buffer plus O(log n) stack frames. Sorts the list in place, like list.sort().
"""
 
from collections.abc import Callable
from typing import Any
 
 
def _identity(item: Any) -> Any:
    return item
 
 
def merge_sort(items: list[Any], key: Callable[[Any], Any] = _identity) -> None:
    buffer: list[Any] = [None] * len(items)
    _sort_range(items, buffer, 0, len(items), key)
 
 
def _sort_range(items: list[Any], buffer: list[Any], low: int, high: int, key: Callable[[Any], Any]) -> None:
    """Sort items[low:high] (high exclusive)."""
    if high - low <= 1:
        return
    mid = (low + high) // 2
    _sort_range(items, buffer, low, mid, key)
    _sort_range(items, buffer, mid, high, key)
    _merge(items, buffer, low, mid, high, key)
 
 
def _merge(items: list[Any], buffer: list[Any], low: int, mid: int, high: int, key: Callable[[Any], Any]) -> None:
    """Merge the sorted halves items[low:mid] and items[mid:high]."""
    for p in range(low, high):
        buffer[p] = items[p]
    i, j, k = low, mid, low
    while i < mid and j < high:
        if key(buffer[i]) <= key(buffer[j]):  # <= takes the left one on ties: stable
            items[k] = buffer[i]
            i += 1
        else:
            items[k] = buffer[j]
            j += 1
        k += 1
    while i < mid:
        items[k] = buffer[i]
        i, k = i + 1, k + 1
    while j < high:
        items[k] = buffer[j]
        j, k = j + 1, k + 1

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

package dev.bekadan.dsa.sorting;
 
import java.util.Comparator;
 
/**
 * Top-down merge sort: stable, O(n log n) comparisons in every case, O(n)
 * auxiliary space for one buffer plus O(log n) stack frames.
 */
public final class MergeSort {
    private MergeSort() {
    }
 
    public static <T> void sort(T[] items, Comparator<? super T> comparator) {
        @SuppressWarnings("unchecked") // Java cannot write new T[n]; the buffer never leaves this class
        T[] buffer = (T[]) new Object[items.length];
        sortRange(items, buffer, 0, items.length, comparator);
    }
 
    /** Sorts items[low..high) (high exclusive). */
    private static <T> void sortRange(T[] items, T[] buffer, int low, int high, Comparator<? super T> comparator) {
        if (high - low <= 1) {
            return;
        }
        int mid = low + (high - low) / 2;
        sortRange(items, buffer, low, mid, comparator);
        sortRange(items, buffer, mid, high, comparator);
        merge(items, buffer, low, mid, high, comparator);
    }
 
    /** Merges the sorted halves items[low..mid) and items[mid..high). */
    private static <T> void merge(T[] items, T[] buffer, int low, int mid, int high, Comparator<? super T> comparator) {
        for (int p = low; p < high; p++) {
            buffer[p] = items[p];
        }
        int i = low, j = mid, k = low;
        while (i < mid && j < high) {
            if (comparator.compare(buffer[i], buffer[j]) <= 0) { // <= takes the left one on ties: stable
                items[k++] = buffer[i++];
            } else {
                items[k++] = buffer[j++];
            }
        }
        while (i < mid) {
            items[k++] = buffer[i++];
        }
        while (j < high) {
            items[k++] = buffer[j++];
        }
    }
}

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

#pragma once
 
#include <cstddef>
#include <functional>
#include <span>
#include <vector>
 
namespace bekadan::dsa {
 
namespace detail {
 
// Merges the sorted halves items[low, mid) and items[mid, high).
template <typename T, typename Less>
void merge(std::span<T> items, std::span<T> buffer, std::size_t low, std::size_t mid, std::size_t high, Less& less) {
    for (std::size_t p = low; p < high; ++p)
        buffer[p] = items[p];
    std::size_t i = low, j = mid, k = low;
    while (i < mid && j < high) {
        if (!less(buffer[j], buffer[i]))  // left <= right takes the left one on ties: stable
            items[k++] = buffer[i++];
        else
            items[k++] = buffer[j++];
    }
    while (i < mid)
        items[k++] = buffer[i++];
    while (j < high)
        items[k++] = buffer[j++];
}
 
// Sorts items[low, high) (high exclusive).
template <typename T, typename Less>
void sort_range(std::span<T> items, std::span<T> buffer, std::size_t low, std::size_t high, Less& less) {
    if (high - low <= 1)
        return;
    std::size_t mid = low + (high - low) / 2;
    sort_range(items, buffer, low, mid, less);
    sort_range(items, buffer, mid, high, less);
    merge(items, buffer, low, mid, high, less);
}
 
}  // namespace detail
 
// Top-down merge sort: stable, O(n log n) comparisons in every case, O(n)
// auxiliary space for one buffer plus O(log n) stack frames.
// `less` is a strict weak ordering, as for std::stable_sort. T must be
// default-constructible and copy-assignable (the buffer starts as T{} values).
template <typename T, typename Less = std::less<>>
void merge_sort(std::span<T> items, Less less = {}) {
    std::vector<T> buffer(items.size());
    detail::sort_range(items, std::span<T>(buffer), 0, items.size(), less);
}
 
}  // namespace bekadan::dsa

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

References