Merge Sort
How merge sort sorts in O(n log n) by splitting, sorting each half and merging, how its variants differ, and what interviewers ask about it.
On this page
Merge sort is a sorting algorithm that splits a list in half, sorts each half, and then merges the two sorted halves into one sorted list. It sorts any input in O(n log n) time, it keeps equal items in their original order, and it needs extra memory proportional to the list. You reach for it when you need a guaranteed running time, a stable sort, or a way to sort data that does not fit in memory.
The merge step is what makes it work. Two sorted lists can be combined into one sorted list in a single pass, because the smallest remaining item is always at the front of one of them. Without that step, sorting each half would leave you with two sorted lists and no cheap way to produce the sorted whole.
How merge sort works
Merge sort is recursive, and it has four steps.
- If the list has 0 or 1 items, it is already sorted, so return it. This is the base case.
- Split the list into a left half and a right half.
- Sort each half by calling merge sort on it.
- Merge the two sorted halves into one sorted list.
Step 3 calls the function that is still being written. This works because each call receives a smaller list, so the calls eventually reach the base case. The comparisons all happen on the way back up, in the merges. Splitting a problem, solving the parts and combining the answers is called divide and conquer.
Tracing a merge
To merge, keep one index at the front of each sorted half, compare the two items they point to, move the smaller one into the output, and advance the index it came from. This is the two-list form of two pointers. The trace below is the last merge in the figure, with i in the left half and j in the right half.
i = 0, j = 0, out = []while i < len(left) and j < len(right): if left[i] <= right[j]: out.append(left[i]); i = i + 1 else: out.append(right[j]); j = j + 1append what is left of left, then of right- left02i152639right01j132738out01234567
- comparisons
- 0
1Both halves are sorted, so the smallest item overall is at the front of one of them, either 2 or 1.
- left02i152639right0113j2738out011234567
- comparisons
- 1
21 is smaller than 2, so take 1 and move
j. - left0215i2639right0113j2738out0112234567
- comparisons
- 2
32 is smaller than 3, so take 2 from the left and move
i. - left0215i2639right011327j38out01122334567
- comparisons
- 3
43 is smaller than 5, so take 3.
- left021526i39right011327j38out011223354567
- comparisons
- 4
55 is smaller than 7, so take 5.
- left02152639iright011327j38out0112233546567
- comparisons
- 5
66 is smaller than 7, so take 6.
- left02152639iright01132738jout01122335465767
- comparisons
- 6
77 is smaller than 9, so take 7.
- left02152639iright01132738jout011223354657687
- comparisons
- 7
88 is smaller than 9, so take 8. The right half is now empty, so the loop stops.
- left02152639iright01132738jout0112233546576879
- comparisons
- 7
9The rest of the other half is sorted and bigger than everything in
out. Copy it without comparing, which here is just the 9. - out0112233546576879
- comparisons
- 7
- items
- 8
10The merge placed 8 items with 7 comparisons. A merge of
nitems needs at most n − 1 comparisons, because each comparison places one item for good.
The code
This version returns a new sorted list and leaves the input unchanged.
function mergeSort(a) {
if (a.length <= 1) return a; // base case
const mid = Math.floor(a.length / 2);
const left = mergeSort(a.slice(0, mid));
const right = mergeSort(a.slice(mid));
return merge(left, right);
}
function merge(left, right) {
const out = [];
let i = 0, j = 0;
while (i < left.length && j < right.length) {
// Taking from the left on ties (<=) keeps the sort stable.
if (left[i] <= right[j]) out.push(left[i++]);
else out.push(right[j++]);
}
// One half is empty, and the rest of the other half is already sorted.
while (i < left.length) out.push(left[i++]);
while (j < right.length) out.push(right[j++]);
return out;
}
mergeSort([6, 2, 9, 5, 1, 8, 3, 7]); // [1, 2, 3, 5, 6, 7, 8, 9]def merge_sort(a):
if len(a) <= 1: # base case
return a
mid = len(a) // 2
left = merge_sort(a[:mid])
right = merge_sort(a[mid:])
return merge(left, right)
def merge(left, right):
out = []
i = j = 0
while i < len(left) and j < len(right):
# Taking from the left on ties (<=) keeps the sort stable.
if left[i] <= right[j]:
out.append(left[i])
i += 1
else:
out.append(right[j])
j += 1
# One half is empty, and the rest of the other half is already sorted.
out.extend(left[i:])
out.extend(right[j:])
return out
merge_sort([6, 2, 9, 5, 1, 8, 3, 7]) # [1, 2, 3, 5, 6, 7, 8, 9]Time and space
Every row of merges in the figure touches all n items once, so each row costs O(n). Halving a list of n items takes about log₂ n steps to reach single items, so there are about log₂ n rows. The total is O(n log n). The splits ignore the values, so a sorted, reversed or random input all take about the same time.
The merge writes into a new list, so merge sort needs O(n) extra space. The recursion itself is only log n calls deep.
There are log n levels of merging, each doing O(n) work, on every input. The merge needs a second list.
Variants and when to use them
Top-down and bottom-up
The code above is top-down: it recurses from the whole list down to single items. The bottom-up version has no recursion. It treats every item as a sorted run of length 1, merges neighbouring runs into runs of length 2, then merges those into runs of length 4, and keeps doubling until one run covers the whole list. It does the same merges in a different order. It is useful when recursion depth is a concern or when you want to avoid function-call overhead, and the running time and space are unchanged.
Merge sort on a linked list
Merge sort suits linked lists better than most sorting algorithms. Merging only walks forward through each list, so it can be done by relinking nodes without any extra list, which brings the extra space down to the O(log n) recursion stack. Finding the middle takes a slow and fast pointer, because a linked list has no index access. Heap sort depends on jumping to arbitrary positions, which a linked list cannot do cheaply, and quicksort loses its in-place advantage there.
Sorting data that does not fit in memory
Merge sort reads each input sequentially, which is the access pattern that disks handle well. An external sort reads chunks small enough to fit in memory, sorts each chunk and writes it to disk as a sorted run, and then merges all of the runs in one pass, keeping only the front item of each run in memory. Databases use this approach for sorting tables that are larger than RAM.
Counting inversions
An inversion is a pair of items where the larger one comes first. You can count them with a small change to merge sort. During a merge, if the item taken comes from the right half, it is smaller than every item still waiting in the left half, so it forms one inversion with each of them. Add the number of remaining left items to the count each time that happens. The total over all merges is the number of inversions, and the running time stays O(n log n) instead of the O(n²) of checking every pair.
Hybrid sorts used by libraries
Python's built-in sort and Java's sort for objects use Timsort, which is a merge sort adapted to real data. It finds runs that are already sorted or reversed, extends short runs with insertion sort, and then merges the runs. On data that is already partly ordered it does far less than n log n work, and it is stable, which is why these libraries choose it for sorting objects.
When merge sort is the wrong choice
If memory is tight, the O(n) extra space is a real cost, and heap sort sorts in place with the same worst-case time. For arrays in memory, quicksort is usually faster in practice because it works in place and uses the cache well, although its worst case is O(n²). For small inputs, a simple insertion sort is quicker than the recursion, which is why library sorts switch to it for short runs. When the values are small integers, counting sort or radix sort avoids comparisons altogether. Merging in place is possible, but the in-place versions are complicated and slow, so they are rarely worth using.
Mistakes when implementing merge sort
In the interview
Merge sort is rarely the answer to a problem by name. It appears in two ways: you are asked to implement it or to explain it, or a problem has a structure that a merge step solves. Look for these signals.
- The problem asks for a sort with a guaranteed O(n log n) worst case or a stable result, or it says the input is a linked list.
- The problem asks you to count pairs of items in the wrong order, such as inversions, or to count for each item how many smaller items come after it. Both are merge sort with a counter added to the merge.
- The problem gives you several sorted lists or arrays and asks for one combined sorted result. That is the merge step on its own.
- The data is too large for memory and arrives in sorted runs, which points to an external merge sort.
These are the questions interviewers usually ask once you have written it.
- "What is the time and space complexity, and why?" The time is O(n log n) in the best, average and worst cases. There are about log n levels of splitting, and each level merges n items in total. The space is O(n) for the merge buffers, plus O(log n) for the recursion.
- "Is it stable? What would break that?" It is stable because the merge takes from the left half on ties, and the left half holds the items that came first. Changing
<=to<would make it unstable. - "Why not use merge sort for everything?" It needs O(n) extra memory and copies every item at every level. Quicksort sorts in place and is usually faster on arrays, and insertion sort is faster on very small or nearly sorted inputs. Many libraries combine merge sort with insertion sort for exactly this reason.
- "Can you make it use O(1) extra space?" There are in-place merge algorithms, but they are complicated and slower in practice. A better answer is to say that if memory is the constraint, heap sort sorts in place in O(n log n), and for linked lists merge sort already needs no extra list.
- "How would you sort a file that is larger than memory?" Read chunks that fit in memory, sort each one and write it out as a run. Then merge all of the runs at once, holding only the front item of each run in memory, usually with a heap to pick the smallest front item.
- "How would you count inversions?" Add a counter to the merge. Each time an item is taken from the right half, add the number of items still left in the left half. The total is the inversion count, in O(n log n).
- "What is the recurrence?" T(n) = 2T(n/2) + O(n): two subproblems of half the size, plus a linear merge. It solves to O(n log n).
You merge [1, 2, 3] with [10, 20, 30]. How many comparisons does the merge loop make?
What is the time complexity of merge sort on a list that is already sorted?
How much extra memory does the merge sort in this lesson need, not counting the recursion stack?
During a merge you take an item from the right half while 3 items are still waiting in the left half. How many inversions does this add?
Related lessons and practice
Trace the full sort of [4, 1, 3, 2] by hand, which takes two merges of pairs and one merge of halves. Then read Quicksort, which does its work while splitting and needs no extra list, and Linked Lists to practise merging two sorted lists.