M13 · Sorting

Merge Sort: Split, Merge and the Auxiliary Buffer

Merge sort splits the array in half until every piece holds one element, then merges sorted pieces back together. Merging two sorted halves is easy and linear, and there are only log n levels of halving, so the whole sort costs O(n log n) no matter what the input looks like.

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

You will be able to

  • Trace the recursion of top-down merge sort, including the call stack and the order in which ranges are sorted.
  • Merge two sorted ranges through an auxiliary buffer and explain each comparison and write.
  • Explain why taking the left element on ties makes merge sort stable, and why stability matters.
  • Derive O(n log n) time from the recurrence T(n) = 2T(n/2) + Θ(n), and O(n) extra space.
  • Say which built-in sorts in C#, Python, Java and C++ are stable and which are not.

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.
  • M11 Recursion — Base cases, the call stack, recursion trees and the first look at memoization.

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

Merging is the easy part. Given two piles of cards, each already sorted, you can produce one sorted pile by repeatedly looking at the two top cards and taking the smaller. You never look further than the tops, and every card is moved exactly once.

Merge sort makes everything else into that easy part:

  1. Split the range in half at mid.
  2. Sort each half, by the same method (recursion).
  3. Merge the two sorted halves.

A range of zero or one elements is already sorted: that is the base case that stops the recursion.

The lab shows three regions at once: the array, the auxiliary buffer, and the call stack, one slab per sortRange call that has started but not yet returned. The coloured brackets behind the array are the ranges of those calls, innermost brightest.

The recursion

sortRange(low, high) sorts the half-open range [low, high). For eight elements the calls happen in this order: sort [0, 8) → sort [0, 4) → sort [0, 2) → sort [0, 1) (base case) → sort [1, 2) (base case) → merge [0, 2) → sort [2, 4) → … The left half is always finished before the right half starts, so the stack never holds more than one path from the whole range down to a single element: at most ⌈log₂ n⌉ + 1 frames. Watch the Max stack depth metric: 4 for eight elements.

Merging through a buffer

You cannot merge two halves in place by simply writing into the array: the first write would overwrite an element that has not been placed yet. This implementation therefore:

  1. Copies [low, high) into the same positions of the buffer (the array slots fade in the lab: their contents are safe in the buffer and may be overwritten).
  2. Walks the two halves of the buffer with i (left) and j (right), writing the smaller front element to items[k].
  3. When one half runs out, copies the rest of the other half without comparing.

The buffer is allocated once, with n slots, and every merge borrows the part under its own range. Allocating a new temporary array in every call would give the same O(n) peak memory but far more allocations.

Stability

A sort is stable if elements that compare equal keep their original relative order. That matters as soon as you sort records by one field: sort orders by date, then stably by customer, and each customer's orders stay in date order.

Merge sort is stable because of one character. On a tie, the merge takes the left element (compare(left, right) <= 0, or in C++ !less(right, left)). Every left element started before every right element, so equal values never overtake each other. Write < instead and the sort still sorts, but it is no longer stable. In the lab, repeated values carry letters (5a, 5b, 5c); run the Equal values stay in order preset and the letters come out in order.

Why it is O(n log n)

Let T(n) be the cost of sorting n elements. Two recursive calls on halves plus a linear merge:

T(n) = 2·T(n/2) + c·n,    T(1) = c

Draw it as a tree. Level 0 is one merge of n elements; level 1 is two merges of n/2; level 2 is four of n/4. Every level does about c·n work in total, and halving reaches 1 after ⌈log₂ n⌉ levels. So T(n) = Θ(n log n). The same recurrence appears again in M29 with the Master theorem.

Concretely, for this implementation:

Measure Bound Note
Comparisons ≤ n·⌈log₂ n⌉ a merge of m elements compares at most m − 1 times
Element writes 2n per level, 2n·⌈log₂ n⌉ for powers of two copy out, merge back
sortRange calls 2n − 1 n base cases plus n − 1 splits
Extra space n buffer slots + O(log n) stack frames O(n)

Unlike quicksort, nothing depends on the input order: sorted, reversed and random inputs all cost Θ(n log n). Sorted input saves comparisons (each merge drains one half early, as the Already sorted preset shows), but this simple version still copies everything at every level. Production merge sorts such as Timsort detect already sorted runs and do much less work on them.

Built-in sorts and stability

Language Stable Not stable
C# Enumerable.OrderBy / ThenBy (LINQ, returns a new sequence) Array.Sort, List<T>.Sort, Span<T>.Sort: introspective sort, documented as unstable
Python list.sort() and sorted(): guaranteed stable (Timsort, a merge sort over natural runs) —
Java Arrays.sort(Object[]), List.sort, Collections.sort: guaranteed stable (a TimSort adaptation) Arrays.sort(int[]) and other primitives: dual-pivot quicksort; stability is meaningless for primitives anyway
C++ std::stable_sort: O(n log n) comparisons with enough extra memory, O(n log² n) without std::sort: O(n log n) comparisons, no stability guarantee

The algorithms named here are implementation details of the current runtimes; the stability guarantee (or its absence) is the documented contract you can rely on.

The teaching implementation

Sort / merge_sort takes a comparison so the tests can sort records by a key and check stability. The four versions differ only where the languages force it: Java cannot create a generic array, so it allocates an Object[] and casts once; C++ fills the buffer with default-constructed values; and Python's version takes a key function like list.sort. All four read one shared fixture file whose tokens such as 3a 3b must come out in their original order, and each is compared with its language's stable built-in sort on 500 random inputs.

Common mistakes

  • < instead of <= in the merge comparison: the output is sorted but no longer stable.
  • Forgetting to drain the remaining half: the elements left in the buffer are lost.
  • Allocating a new buffer in every merge: correct but slow; allocate once and pass it down.
  • Assuming the built-in sort is stable. In C# Array.Sort and List<T>.Sort are not; use OrderBy or include a tie-breaking key.
  • Splitting on (low + high) / 2 in fixed-width integers: the same overflow as in binary search.

Edge cases

  • Empty array and one element: the first call is already a base case; nothing is compared or written.
  • All elements equal: every comparison is a tie and takes the left element; the order is unchanged.
  • Odd lengths: mid rounds down, so the left half is the smaller one and the recursion tree is slightly unbalanced (the Odd length preset).

Worked practice

1. How many element comparisons can merging a sorted half of 3 with a sorted half of 5 need at most?

Answer

7 (= 3 + 5 − 1). Each comparison places one element; once one half is empty, the last elements are copied without comparing, and at least one element is always copied that way.

2. Why is the call stack depth O(log n) even though there are 2n − 1 calls?

Answer

Calls run one after another, not all at once. A frame is on the stack only while one of its descendants is running, so the stack holds one root-to-leaf path of the recursion tree, which has ⌈log₂ n⌉ + 1 levels.

3. You sort people by name with a stable sort, then by age with a stable sort. In what order are people of the same age?

Answer

By name. The second, stable sort keeps the name order among people whose ages are equal. Sorting by the least significant key first and the most significant key last is how multi-key sorting with stable sorts works.

Summary

  • Merge sort splits until ranges are trivial, then merges sorted halves in linear time.
  • Θ(n log n) time in every case; O(n) extra space for the buffer plus O(log n) stack.
  • Taking the left element on ties (<=) makes it stable.
  • Python's and Java's object sorts are stable; C#'s Array.Sort and C++'s std::sort are not.

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