Merge Sort: Dividing, Merging and Cost
Split the array in half until single values remain, then merge sorted runs pairwise. Every level of merging is linear and there are log n levels.
How It Works
- If the array has 0 or 1 values, it is already sorted: return it
- Split it at the midpoint into a left half and a right half
- Sort each half with the same procedure
- Merge the two sorted halves: repeatedly take the smaller of their two front values
- When one half runs out, copy the rest of the other
Merge sort is the standard divide and conquer sort. The split does no comparing at all; it just cuts at the middle. All the work happens on the way back up, in the merge.
The merge is correct because both runs are already sorted: the smaller of the two front values is the smallest value not yet placed. So each comparison puts one value in its final place in the output, and merging runs with n values in total takes at most n − 1 comparisons.
On [38, 27, 43, 3] the array splits into [38, 27] and [43, 3], then into four single values. Merging pairs gives [27, 38] and [3, 43], and the final merge takes 3, 27, 38 and then copies 43: [3, 27, 38, 43] after 5 comparisons.
- The midpoint split works on any length; odd lengths give halves that differ by one
- The base case must include length 1, or the recursion never stops
Merge Sort Time Complexity
Halving reaches length 1 after about log₂ n levels. On each level every value takes part in exactly one merge, so each level costs O(n) whatever the data looks like. Multiplying gives O(n log n), the same answer the recurrence T(n) = 2T(n/2) + O(n) gives through the master theorem.
- Time complexity: best, average and worst O(n log n)
- Space complexity: O(n) for the merge buffer, plus O(log n) recursion stack
The split depends only on positions, never on values, so no input can make it lopsided. The number of comparisons does vary a little: merging two runs of k values takes between k and 2k − 1 comparisons, so sorted input needs about half as many as random input. But every value is still copied once per level, so the running time stays Θ(n log n) on every input. For n = 1,000,000 that is about 20 levels.
That guarantee is the reason to choose merge sort: there is no bad input to guard against, unlike quick sort.
- Allocate one buffer of size n and reuse it in every merge; allocating inside each call is much slower
- If the last value of the left run is ≤ the first of the right run, the two are already in order and the merge can be skipped
Stability and Common Bugs
Merge sort is stable: equal values keep their input order. That depends on one character. When the two front values are equal, the merge must take from the left run, which is what if left[i] <= right[j] does. Writing < takes the right one first and silently reverses equal keys.
The other common bug is in the base case or the split. With mid = len // 2 and a base case of only len == 0, an array of length 1 splits into [] and itself, and the recursion never ends. In languages with fixed-size integers, computing (lo + hi) / 2 can overflow for huge arrays; lo + (hi − lo) / 2 cannot.
Forgetting to copy the leftover run is the third: when one run is empty, the remaining values of the other are already sorted and must be appended, not dropped.
- Stability matters when sorting records by one key after another, for example by date and then by name
- Practice: merge sorted array is the merge step alone
Terms, operations, and practical uses
Core mechanics
- Divide stepSplitting positionally at the midpoint — no comparison happens here, which is why the split is always balanced.
- Merge stepWalking two sorted runs with one index each, taking the smaller front element. All the work lives here.
- Auxiliary arrayThe O(n) scratch buffer merging needs; the reason merge sort is not in-place.
Properties
- StableTaking from the left run on ties preserves the original order of equal keys.
- Θ(n log n) alwayslog n levels of halving and O(n) copying per level, on every input; only the comparison count varies.
- Sequential accessMerging reads both runs front to back, which suits linked lists and external data on disk.
Where it is used
- External sortingSorting data larger than memory: sort runs that fit, then merge them from disk.
- TimsortPython's
sortedand Java'sArrays.sortfor objects — merge sort with runs detected in the input. - Linked listsThe preferred O(n log n) sort for lists, since merging needs only pointer rewiring and no random access.
Code in Python, C++ and Java
def merge_sort(values):
if len(values) <= 1:
# a run of 0 or 1 is already sorted
return values
mid = len(values) // 2
left = merge_sort(values[:mid])
right = merge_sort(values[mid:])
return merge(left, right)
def merge(left, right):
merged, i, j = [], 0, 0
while i < len(left) and j < len(right):
if left[i] <= right[j]:
# <= keeps the sort stable
merged.append(left[i])
i += 1
else:
merged.append(right[j])
j += 1
merged.extend(left[i:]) # one run is empty; copy the rest
merged.extend(right[j:])
return merged
print(merge_sort([38, 27, 43, 3]))#include <iostream>
#include <vector>
std::vector<int> merge(const std::vector<int>& left,
const std::vector<int>& right) {
std::vector<int> merged;
merged.reserve(left.size() + right.size());
std::size_t i = 0, j = 0;
while (i < left.size() && j < right.size()) {
if (left[i] <= right[j]) merged.push_back(left[i++]); // <= is stable
else merged.push_back(right[j++]);
}
while (i < left.size()) merged.push_back(left[i++]);
while (j < right.size()) merged.push_back(right[j++]);
return merged;
}
std::vector<int> mergeSort(const std::vector<int>& values) {
if (values.size() <= 1) return values;
const std::size_t mid = values.size() / 2;
return merge(mergeSort({values.begin(), values.begin() + mid}),
mergeSort({values.begin() + mid, values.end()}));
}
int main() {
std::vector<int> sorted = mergeSort({38, 27, 43, 3});
std::cout << '[';
for (std::size_t i = 0; i < sorted.size(); ++i) std::cout << (i ? ", " : "") << sorted[i];
std::cout << "]\n";
}import java.util.Arrays;
public class Main {
static int[] mergeSort(int[] values) {
if (values.length <= 1) return values; // 0 or 1 is already sorted
int mid = values.length / 2;
int[] left = mergeSort(Arrays.copyOfRange(values, 0, mid));
int[] right = mergeSort(Arrays.copyOfRange(values, mid, values.length));
return merge(left, right);
}
static int[] merge(int[] left, int[] right) {
int[] merged = new int[left.length + right.length];
int i = 0, j = 0, k = 0;
while (i < left.length && j < right.length) {
if (left[i] <= right[j]) merged[k++] = left[i++]; // <= is stable
else merged[k++] = right[j++];
}
while (i < left.length) merged[k++] = left[i++];
while (j < right.length) merged[k++] = right[j++];
return merged;
}
public static void main(String[] args) {
System.out.println(Arrays.toString(mergeSort(new int[]{38, 27, 43, 3})));
}
}Step through it
Running on [38, 27, 43, 3]
Bottom-Up Merge Sort
The recursion can be dropped entirely. Bottom-up merge sort treats the array as n runs of length 1, merges neighbours into runs of length 2, then 4, then 8, until one run covers the array. It does the same merges as the recursive version, level by level, with two plain loops and no call stack.
On linked lists merging only relinks nodes, so no buffer is needed, and the bottom-up form sorts a list in O(n log n) time with O(1) extra space. That is why merge sort is the usual way to sort a linked list; see sort list.
The same merge is the core of external sorting, for data larger than memory: sort chunks that fit, write them out as runs, then merge the runs while reading each one front to back. It is also the base of Timsort, used by Python's sorted and by Java for objects, which finds runs already present in the input and merges them.
- Counting inversions is a merge sort that counts how many right-run values jump ahead of left-run values: count inversions
- Merging k sorted lists at once uses a heap: merge k sorted lists
Merge Sort vs Quick Sort
Both are O(n log n) divide and conquer sorts, but they put the work in opposite places. Merge sort splits blindly and does its work in the merge; quick sort does its work in the partition and then needs no merge.
Quick sort is usually faster on arrays in memory: it sorts in place, touches less memory, and its inner loop is very tight. Its worst case is O(n²) when pivots are chosen badly, which libraries avoid with random or median-of-three pivots and with introsort's fall-back to heap sort. Merge sort wins when you need stability, a guaranteed bound, linked lists, or data on disk.
| Merge sort | Quick sort | |
|---|---|---|
| Worst case | O(n log n) | O(n²) |
| Extra space | O(n) buffer | O(log n) stack on average |
| Stable | yes | no |
| Where the work is | merging | partitioning |
| Best fit | linked lists, external data, stable sorts | arrays in memory |
- For tiny ranges both hand over to insertion sort, which is faster below about 16 values