The three sorts so far are all O(n²). They are fine for small arrays, but for a million values they could run for hours. Merge Sort is our first O(n log n) algorithm, and it gets there with a powerful idea called divide and conquer:
- Divide the problem into smaller pieces.
- Conquer each piece. Small pieces are easy to solve.
- Combine the answers.
By the end of this lesson, you will understand:
- How Merge Sort splits and merges
- Why merging two sorted lists is easy
- How to write it with recursion
- Why it is always
O(n log n) - What it costs: extra memory
What Is Merge Sort?
Merge Sort is built on one simple observation: merging two lists that are already sorted is easy. You just keep comparing the front of each list and take the smaller one.
So Merge Sort:
- Splits the array in half, again and again, until every piece has just one value. A single value is always sorted.
- Merges the pieces back together in pairs, each time producing a bigger sorted piece.
- Keeps merging until the whole array is one sorted piece.
Watch it below. The blue band shows the part currently being split or merged, and i and j point at the front of the two halves being merged.
The Exam Papers Analogy
A teacher has two piles of exam papers. Each pile is already sorted by roll number, smallest on top.
1. Look at Both Top Papers
Compare the roll numbers on top of the two piles.
2. Take the Smaller One
Move the paper with the smaller roll number onto a new pile.
3. Repeat
Keep comparing the two tops and taking the smaller.
4. One Pile Runs Out
When one pile is empty, put the rest of the other pile on top. It's already sorted, so it's done.
That is merging. Merge Sort's trick is that by splitting all the way down to single papers, every pile it ever merges is guaranteed to be sorted.
Tracing It by Hand
Let's sort [5, 1, 4, 2, 8].
Step 1: Split until every piece has one value
[5, 1, 4, 2, 8]
/ \
[5, 1, 4] [2, 8]
/ \ / \
[5, 1] [4] [2] [8]
/ \
[5] [1]
The middle is mid = (left + right) / 2, rounded down, so with an odd number of values the left half gets the extra one.
Step 2: Merge the pieces back together
[5] + [1] → [1, 5]
[1, 5] + [4] → [1, 4, 5]
[2] + [8] → [2, 8]
[1, 4, 5] + [2, 8] → [1, 2, 4, 5, 8]
The Final Merge, in Detail
Merging [1, 4, 5] and [2, 8]:
| Compare fronts | Take | Merged so far |
|---|---|---|
| 1 and 2 | 1 | [1] |
| 4 and 2 | 2 | [1, 2] |
| 4 and 8 | 4 | [1, 2, 4] |
| 5 and 8 | 5 | [1, 2, 4, 5] |
| left side used up | copy the rest: 8 | [1, 2, 4, 5, 8] |
The whole sort takes 8 comparisons and 12 writes. Every merge writes each of its values back into the array once, which is why the number of writes doesn't depend on the order of the input.
Merge Sort in Code
Merge Sort is written with recursion: mergeSort calls itself to sort each half. The recursion stops when a piece has just one value, which is already sorted.
import java.util.Arrays;
public class Main {
static void mergeSort(int[] a, int left, int right) {
if (left >= right) {
return; // 0 or 1 value: already sorted
}
int mid = left + (right - left) / 2;
mergeSort(a, left, mid); // sort the left half
mergeSort(a, mid + 1, right); // sort the right half
merge(a, left, mid, right); // merge the two sorted halves
}
static void merge(int[] a, int left, int mid, int right) {
int[] L = Arrays.copyOfRange(a, left, mid + 1);
int[] R = Arrays.copyOfRange(a, mid + 1, right + 1);
int i = 0, j = 0, k = left;
while (i < L.length && j < R.length) {
if (L[i] <= R[j]) { // <= keeps equal values in order (stable)
a[k++] = L[i++];
} else {
a[k++] = R[j++];
}
}
while (i < L.length) a[k++] = L[i++]; // copy what's left of L
while (j < R.length) a[k++] = R[j++]; // copy what's left of R
}
public static void main(String[] args) {
int[] marks = {5, 1, 4, 2, 8};
mergeSort(marks, 0, marks.length - 1);
System.out.println(Arrays.toString(marks)); // [1, 2, 4, 5, 8]
}
}Let's connect the code to the trace:
mergeSortdoes the splitting. It findsmid, sorts each half by calling itself, then merges.if (left >= right) returnis the base case: a piece with one value (or none) is already sorted, so the recursion stops there.mergecopies each half into a temporary array,LandR, then repeatedly takes the smaller front value.iandjare the fronts, andkis where the next value is written.- The two
whileloops at the end copy whatever is left once one half is used up.
How Fast Is Merge Sort?
The array is cut in half again and again, so there are about log₂ n levels of splitting. At every level, merging touches all n values once. That gives n × log₂ n work in total.
| Case | Example | Time | Why |
|---|---|---|---|
| Best | Already sorted | O(n log n) | It still splits and merges every level |
| Average | Random order | O(n log n) | Same structure |
| Worst | Any order | O(n log n) | Same structure, guaranteed |
| Extra memory | Any | O(n) | The temporary arrays L and R |
Merge Sort's speed is guaranteed: no input can make it slow. Try Sorted and Reversed in the animation. The number of writes is identical, and the comparisons barely change.
The price is memory. Merge Sort is not in-place: it needs extra space roughly as big as the array to hold the halves while merging.
Merge Sort is stable. On a tie,
L[i] <= R[j]takes the value from the left half first, so equal values keep their original order.
Common Mistakes
1. Splitting Into the Wrong Ranges
The halves must be [left, mid] and [mid + 1, right]. Splitting into [left, mid - 1] and [mid, right] looks similar, but for two values mid equals left. The right half is then the same as the original range, so the recursion calls itself on the same range forever.
2. Forgetting the Leftovers
When one half runs out, the other still has values in it. Without the two copying loops at the end, those values are simply lost.
3. Using < Instead of <=
L[i] < R[j] still sorts correctly, but on a tie it takes from the right half first, which breaks stability.
When Should You Use Merge Sort?
Good for:
- Large amounts of data, when you need speed guaranteed
- Sorts that must be stable, like sorting by marks after sorting by name
- Data too big to fit in memory, sorted in chunks on disk and merged, called external sorting
- Linked lists, where it doesn't need the extra array
Not good for:
- Situations where memory is very limited, because of the
O(n)extra space - Tiny arrays, where Insertion Sort is simpler and often faster
In the next lesson, we will learn Quick Sort, which also divides and conquers, but sorts in place and is usually even faster in practice.
Remember This
If you remember only one thing from this lesson, remember: Merge Sort splits the array in half until single values remain, then merges sorted halves back together. It is always O(n log n) and stable, but needs O(n) extra memory.