C# Merge Sort
last modified November 6, 2026
In this article we implement the merge sort algorithm in C#. We write the
recursive and the iterative version, trace how the array is split and merged,
use merge sort as a stable sort for records, and compare its speed with
Array.Sort.
Sorting is arranging the elements of a collection in a specific order, for instance from the smallest to the largest. A sorting algorithm is the sequence of steps that produces this order.
Merge sort algorithm
Merge sort is a divide and conquer algorithm, invented by John von Neumann in 1945. It splits the array into two halves, sorts each half recursively, and merges the two sorted halves into one sorted array. An array of one element is sorted by definition, which ends the recursion.
Merging two sorted sequences is simple: we repeatedly compare their first
elements and take the smaller one. The merge of n elements takes
O(n) time, and the array is halved logâ‚‚ n times.
| Property | Value |
|---|---|
| Best, average and worst case | O(n log n) |
| Extra memory | O(n) for arrays |
| Stable | yes |
Merge sort has a guaranteed O(n log n) running time and is stable. Variants of it are used for stable sorting in many languages, for instance Timsort in Python and Java.
C# merge sort example
The first example is the classic top-down merge sort.
int[] nums = [38, 27, 43, 3, 9, 82, 10, 1];
MergeSort(nums);
Console.WriteLine(string.Join(" ", nums));
static void MergeSort(int[] arr)
{
int[] buffer = new int[arr.Length];
Sort(arr, buffer, 0, arr.Length - 1);
}
static void Sort(int[] arr, int[] buffer, int lo, int hi)
{
if (lo >= hi) return;
int mid = lo + (hi - lo) / 2;
Sort(arr, buffer, lo, mid);
Sort(arr, buffer, mid + 1, hi);
Merge(arr, buffer, lo, mid, hi);
}
static void Merge(int[] arr, int[] buffer, int lo, int mid, int hi)
{
Array.Copy(arr, lo, buffer, lo, hi - lo + 1);
int i = lo, j = mid + 1, k = lo;
while (i <= mid && j <= hi)
{
arr[k++] = buffer[i] <= buffer[j] ? buffer[i++] : buffer[j++];
}
while (i <= mid) arr[k++] = buffer[i++];
while (j <= hi) arr[k++] = buffer[j++];
}
The array is sorted in place, with the help of a buffer of the same size.
int[] buffer = new int[arr.Length]; Sort(arr, buffer, 0, arr.Length - 1);
The buffer is allocated once and shared by all recursive calls. Allocating new arrays in each call is simpler but much slower.
int mid = lo + (hi - lo) / 2; Sort(arr, buffer, lo, mid); Sort(arr, buffer, mid + 1, hi); Merge(arr, buffer, lo, mid, hi);
The range from lo to hi is split in the middle. The
form lo + (hi - lo) / 2 cannot overflow, unlike
(lo + hi) / 2.
Array.Copy(arr, lo, buffer, lo, hi - lo + 1);
The two sorted halves are copied to the buffer and merged back into the original array.
while (i <= mid && j <= hi)
{
arr[k++] = buffer[i] <= buffer[j] ? buffer[i++] : buffer[j++];
}
while (i <= mid) arr[k++] = buffer[i++];
while (j <= hi) arr[k++] = buffer[j++];
The smaller of the two front elements is written to the array. When one half runs out, the rest of the other half is copied.
$ dotnet run 1 3 9 10 27 38 43 82
Splits and merges
The next example prints each split and merge. For clarity, it creates new arrays instead of using a buffer.
int[] nums = [5, 2, 8, 1, 9, 3];
Sort(nums, 0);
static int[] Sort(int[] arr, int depth)
{
string indent = new(' ', depth * 2);
if (arr.Length <= 1)
{
return arr;
}
int mid = arr.Length / 2;
Console.WriteLine($"{indent}split [{string.Join(" ", arr)}]");
int[] left = Sort(arr[..mid], depth + 1);
int[] right = Sort(arr[mid..], depth + 1);
int[] merged = Merge(left, right);
Console.WriteLine($"{indent}merge [{string.Join(" ", left)}] + [{string.Join(" ", right)}] -> [{string.Join(" ", merged)}]");
return merged;
}
static int[] Merge(int[] left, int[] right)
{
int[] result = new int[left.Length + right.Length];
int i = 0, j = 0, k = 0;
while (i < left.Length && j < right.Length)
{
result[k++] = left[i] <= right[j] ? left[i++] : right[j++];
}
while (i < left.Length) result[k++] = left[i++];
while (j < right.Length) result[k++] = right[j++];
return result;
}
The indentation shows the depth of the recursion.
int[] left = Sort(arr[..mid], depth + 1); int[] right = Sort(arr[mid..], depth + 1);
The range operator creates copies of the two halves.
The array is split until the parts have one element. Then the parts are merged in pairs on the way back from the recursion.
$ dotnet run
split [5 2 8 1 9 3]
split [5 2 8]
split [2 8]
merge [2] + [8] -> [2 8]
merge [5] + [2 8] -> [2 5 8]
split [1 9 3]
split [9 3]
merge [9] + [3] -> [3 9]
merge [1] + [3 9] -> [1 3 9]
merge [2 5 8] + [1 3 9] -> [1 2 3 5 8 9]
Stable merge sort
A sorting algorithm is stable if elements with equal keys keep their original relative order. In the following example, we sort orders by their total in descending order.
Order[] orders =
[
new(1, "Alice", 120m), new(2, "Bob", 80m), new(3, "Carol", 120m),
new(4, "Dave", 45m), new(5, "Eve", 80m), new(6, "Frank", 120m),
];
MergeSort(orders, (a, b) => b.Total.CompareTo(a.Total));
foreach (var o in orders)
{
Console.WriteLine($"{o.Total,6} #{o.Id} {o.Customer}");
}
static void MergeSort<T>(T[] arr, Comparison<T> compare)
{
T[] buffer = new T[arr.Length];
Sort(0, arr.Length - 1);
void Sort(int lo, int hi)
{
if (lo >= hi) return;
int mid = lo + (hi - lo) / 2;
Sort(lo, mid);
Sort(mid + 1, hi);
Array.Copy(arr, lo, buffer, lo, hi - lo + 1);
int i = lo, j = mid + 1, k = lo;
while (i <= mid && j <= hi)
{
arr[k++] = compare(buffer[i], buffer[j]) <= 0 ? buffer[i++] : buffer[j++];
}
while (i <= mid) arr[k++] = buffer[i++];
while (j <= hi) arr[k++] = buffer[j++];
}
}
record Order(int Id, string Customer, decimal Total);
The generic method takes a Comparison<T> delegate. The
recursive part is a local function that captures the array, the buffer, and
the delegate.
arr[k++] = compare(buffer[i], buffer[j]) <= 0 ? buffer[i++] : buffer[j++];
On a tie, the element from the left half is taken first. This is what makes
the sort stable: the orders with the same total stay sorted by their id. With
< 0, the sort would not be stable.
$ dotnet run
120 #1 Alice
120 #3 Carol
120 #6 Frank
80 #2 Bob
80 #5 Eve
45 #4 Dave
Bottom-up merge sort
The bottom-up version needs no recursion. It merges neighbouring runs of width 1, then of width 2, 4, and so on, until the run covers the whole array.
int[] nums = [14, 7, 3, 12, 9, 11, 6, 2, 10];
MergeSort(nums);
static void MergeSort(int[] arr)
{
int n = arr.Length;
int[] src = arr;
int[] dst = new int[n];
for (int width = 1; width < n; width *= 2)
{
for (int lo = 0; lo < n; lo += 2 * width)
{
int mid = Math.Min(lo + width, n);
int hi = Math.Min(lo + 2 * width, n);
int i = lo, j = mid, k = lo;
while (i < mid && j < hi) dst[k++] = src[i] <= src[j] ? src[i++] : src[j++];
while (i < mid) dst[k++] = src[i++];
while (j < hi) dst[k++] = src[j++];
}
(src, dst) = (dst, src);
Console.WriteLine($"width {width,2}: {string.Join(" ", src)}");
}
if (!ReferenceEquals(src, arr))
{
Array.Copy(src, arr, n);
}
}
We print the array after each round of merges.
int mid = Math.Min(lo + width, n); int hi = Math.Min(lo + 2 * width, n);
The run that starts at lo is merged with the following run. The
last runs may be shorter, so the bounds are limited by the array length.
(src, dst) = (dst, src);
Instead of copying the merged data back after each round, the two arrays swap their roles.
if (!ReferenceEquals(src, arr))
{
Array.Copy(src, arr, n);
}
After an odd number of rounds, the sorted data is in the helper array and is copied back to the input array.
$ dotnet run width 1: 7 14 3 12 9 11 2 6 10 width 2: 3 7 12 14 2 6 9 11 10 width 4: 2 3 6 7 9 11 12 14 10 width 8: 2 3 6 7 9 10 11 12 14
Merge sort vs Array.Sort
In the last example, we sort a million random integers with merge sort,
Array.Sort, and the LINQ Order method.
#:property PublishAot=false
using System.Diagnostics;
var rnd = new Random(17);
int[] data = [.. Enumerable.Range(0, 1_000_000).Select(_ => rnd.Next())];
int[] a = [.. data];
var sw = Stopwatch.StartNew();
MergeSort(a);
Console.WriteLine($"Merge sort: {sw.ElapsedMilliseconds} ms");
int[] b = [.. data];
sw.Restart();
Array.Sort(b);
Console.WriteLine($"Array.Sort: {sw.ElapsedMilliseconds} ms");
sw.Restart();
int[] c = [.. data.Order()];
Console.WriteLine($"LINQ Order: {sw.ElapsedMilliseconds} ms");
Console.WriteLine($"Same result: {a.SequenceEqual(b) && b.SequenceEqual(c)}");
static void MergeSort(int[] arr)
{
int[] buffer = new int[arr.Length];
Sort(arr, buffer, 0, arr.Length - 1);
}
static void Sort(int[] arr, int[] buffer, int lo, int hi)
{
if (lo >= hi) return;
int mid = lo + (hi - lo) / 2;
Sort(arr, buffer, lo, mid);
Sort(arr, buffer, mid + 1, hi);
Array.Copy(arr, lo, buffer, lo, hi - lo + 1);
int i = lo, j = mid + 1, k = lo;
while (i <= mid && j <= hi) arr[k++] = buffer[i] <= buffer[j] ? buffer[i++] : buffer[j++];
while (i <= mid) arr[k++] = buffer[i++];
while (j <= hi) arr[k++] = buffer[j++];
}
All three results are compared with SequenceEqual.
#:property PublishAot=false
File-based apps are published with Native AOT by default. The directive turns this off, so the release build does not pull in the AOT compiler package.
We run the program in the Release configuration. Merge sort is about three
times slower than Array.Sort. Both are O(n log n), but the
built-in method sorts in place without the copying and uses insertion sort for
small partitions. LINQ Order is stable; for primitive types,
where stability makes no difference, it is about as fast as
Array.Sort.
$ dotnet run -c Release benchmark.cs Merge sort: 206 ms Array.Sort: 64 ms LINQ Order: 66 ms Same result: True
Source
In this article we have implemented the merge sort algorithm in C#.
Other sorting algorithms in C#:
- Bubble sort
- Selection sort
- Insertion sort
- Shell sort
- Quick sort
- Heap sort
- Counting sort
- Radix sort
- Bucket sort
Author
List all C# tutorials.