Merge sort splits the input in half, sorts each half, then merges the two sorted halves into one. John von Neumann described it in 1945. It always runs in O(n log n), whatever the input looks like, and it is stable: elements that compare as equal keep their original order. That second property is the main reason to pick it over quick sort.
The version below sorts any T that implements IComparable<T>, works on arrays and Span<T>, and allocates one buffer for the whole sort instead of two new arrays on every merge.
Usage
int[] numbers = { 1, 5, 4, 11, 20, 8, 2, 98, 90, 16 };
MergeSort.Sort(numbers);
Console.WriteLine(string.Join(", ", numbers));
// 1, 2, 4, 5, 8, 11, 16, 20, 90, 98
The same call works for string[], DateTime[] or your own types, as long as they implement IComparable<T>.
Implementation
public static class MergeSort
{
public static void Sort<T>(T[] items) where T : IComparable<T>
=> Sort(items.AsSpan());
public static void Sort<T>(Span<T> items) where T : IComparable<T>
{
if (items.Length < 2) return;
// One scratch buffer for the whole sort.
Span<T> buffer = new T[items.Length];
SortCore(items, buffer);
}
private static void SortCore<T>(Span<T> items, Span<T> buffer) where T : IComparable<T>
{
if (items.Length < 2) return;
int mid = items.Length / 2;
SortCore(items[..mid], buffer[..mid]);
SortCore(items[mid..], buffer[mid..]);
// The halves are already in order: nothing to merge.
if (items[mid - 1].CompareTo(items[mid]) <= 0) return;
Merge(items, mid, buffer);
}
private static void Merge<T>(Span<T> items, int mid, Span<T> buffer) where T : IComparable<T>
{
// Copy the left half out of the way. The right half stays where it is.
Span<T> left = buffer[..mid];
items[..mid].CopyTo(left);
int i = 0, j = mid, k = 0;
while (i < left.Length && j < items.Length)
{
// "<=" takes from the left half on ties, which keeps the sort stable.
if (left[i].CompareTo(items[j]) <= 0)
items[k++] = left[i++];
else
items[k++] = items[j++];
}
// Whatever is left of the right half is already in place.
left[i..].CopyTo(items[k..]);
}
}
How it works
Splitting. SortCore cuts the span in half and recurses until each piece has one element, which is sorted by definition. Recursion depth is about logâ‚‚ n, so even a hundred million elements only go around 27 levels deep. Unlike quick sort, there is no bad input that makes it deeper.
Merging. The original version of this post copied both halves into two new arrays on every merge, which creates a lot of short-lived garbage. Here only the left half is copied, into a slice of a buffer allocated once at the start. The merge then writes back into items from the front. The write position k can never overtake the read position j in the right half, so nothing is overwritten before it has been read.
Skipping merges. If the last element of the left half is not greater than the first element of the right half, the two halves are already in order and the merge is skipped. On sorted or nearly sorted data this turns most merges into a single comparison.
Stability. When the two candidates are equal, the merge takes the one from the left half. Change <= 0 to < 0 and the sort is no longer stable.
Complexity
| Case | Time | Extra space |
|---|---|---|
| Best (already sorted) | O(n) with the skip check | O(n) |
| Average | O(n log n) | O(n) |
| Worst | O(n log n) | O(n) |
The O(n) extra space is the price of the guaranteed O(n log n). Quick sort needs only O(log n) but can degrade on unlucky input.
When to use merge sort
Use it when you need a stable sort with predictable timing, or when the data does not fit in memory: external sorting of large files is almost always a merge of sorted chunks, and merging works just as well on streams and linked lists as on arrays.
For everyday code, remember that Array.Sort and List<T>.Sort are not stable. If you need stability and do not want to maintain your own sort, LINQ’s OrderBy and ThenBy are documented as stable, at the cost of allocating a new sequence. Since .NET 7 you can write items.Order() when the type’s default comparison is what you want.
1 thought on “Merge Sort in C#: A Generic, Stable Implementation”