Algorithm · Sorting and selection · Θ(n log n)
Merge sort
Split in half, sort each half, merge the two sorted halves. Θ(n log n) on every input, stable, with O(n) extra memory.
The full derivation, edge cases and exercises are in the lesson Merge sort: split, merge and the auxiliary buffer. Open it full width in the playground.
On this page
The idea
Divide and conquer in its cleanest form: the recursion splits until single elements remain, and the merge step combines two sorted runs in linear time by repeatedly taking the smaller front element. log₂ n levels of linear merging give Θ(n log n).
Taking from the left run on ties keeps equal elements in order, which is why stable library sorts (Java’s object sort, Python’s Timsort) are merge-based.
Steps
- If the range has fewer than two elements, it is sorted.
- Sort the left half and the right half recursively.
- Merge the halves through a buffer, taking from the left on ties.
Invariants
What holds at every step; the correctness argument rests on these.
- During a merge, the output so far is the smallest elements of both runs, in order.
- Each recursion level touches every element once.
Complexity
| Case | Time | Extra space |
|---|---|---|
| All cases | Θ(n log n) | O(n) buffer + O(log n) stack |
When to use it
Use it when
- You need a guaranteed O(n log n) and stability.
- Sorting linked lists or data that does not fit in memory (external merge sort).
Avoid it when
- Memory is tight and stability does not matter: heap sort or quicksort sort in place.
Step through it
The interactive lab for merge sort: custom and seeded inputs, stepping forward and backward, with the active line highlighted in the code.
Implementation in four languages
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
Learn more
Lessons
- Merge sort: split, merge and the auxiliary buffer· M13 Sorting
- What built-in sorts actually do· M13 Sorting
Data structures it uses
Comparisons
- Bubble sort vs insertion sort· Two quadratic, stable, in-place sorts on one array, with merge sort as an optional third lane. Counts are compared, not timed.
Problems, patterns and exercises
- ProblemMerge two sorted lists into the first one· beginner · O(m + n)
- PatternSort and merge intervals· O(n log n)
- Complexity exerciseTwo halves plus linear work· Θ(n log n)
- PatternGreedy choice after sorting· O(n log n)