Merge sort an array
Sort an integer array in ascending order using merge sort.
Course progress
Problem 77 of 100
Example → approach → runnable solution
Worked example
See the problem in action
Trace a concrete input through to the verified result.
Example input
numbers = [38, 27, 43, 3, 9, 82, 10]
Expected output
3 9 10 27 38 43 82
What is happening?
Split the array into single-value ranges, then repeatedly merge neighboring sorted ranges to build the final ascending order.
Solution strategy
Build the right mental model
Recursively sort both halves, then merge them into a temporary buffer and copy the ordered range back.
Core concepts
sorting · divide and conquer
Complexity
Time O(n log n), space O(n), with O(log n) recursive stack depth.
Runnable solution
Learn from working code
Compare languages, copy the code, or open it in the compiler.
Complete C# solution for merge-sort
using System;
class Program
{
static void MergeSort(int[] numbers, int[] buffer, int left, int right)
{
if (left >= right) return;
int middle = left + (right - left) / 2;
MergeSort(numbers, buffer, left, middle);
MergeSort(numbers, buffer, middle + 1, right);
int i = left, j = middle + 1, write = left;
while (i <= middle && j <= right)
buffer[write++] = numbers[i] <= numbers[j] ? numbers[i++] : numbers[j++];
while (i <= middle) buffer[write++] = numbers[i++];
while (j <= right) buffer[write++] = numbers[j++];
for (int index = left; index <= right; index++) numbers[index] = buffer[index];
}
static void Main()
{
int[] values = { 38, 27, 43, 3, 9, 82, 10 };
MergeSort(values, new int[values.Length], 0, values.Length - 1);
Console.WriteLine(string.Join(" ", values));
}
}Knowledge check
Questions students often ask
What is the main idea behind merge sort an array?
Recursively sort both halves, then merge them into a temporary buffer and copy the ordered range back.
What is the time and space complexity of this solution?
Time O(n log n), space O(n), with O(log n) recursive stack depth.
Do all language tabs solve the same problem?
Yes. Every program uses the same example and produces the verified output shown on this page. The syntax and a few language-specific data structures differ.