Merge sort is a divide-and-conquer sorting algorithm that splits an array into halves until single values remain and then merges the sorted parts back together. It takes O(n log n) time in every case, needs O(n) extra space and is stable. This page explains how it works, with step-by-step animations of the left half, the right half and the final merge from the VisiGrab app.
// how merge sort works
Merge sort is a divide-and-conquer sorting algorithm. It splits an array into halves until single values remain, then merges sorted parts back into one sorted array. John von Neumann described it in 1945. It takes O(n log n) time in every case and O(n) extra space, and it is stable.
Each call sorts one part of the array in three steps. The diagrams show them on 8, 0, 5, 2, the left half of the app's default array.
1. Divide: split the part at its middle.
2. Conquer: sort both halves the same way. A single value is already sorted, so the recursion stops there.
3. Combine: merge the two sorted halves.
Merging uses two markers, one per half. In the app they are the yellow and green "min" labels over each half's first value not yet merged; in the pseudocode below they are the indices i and j. Each half is sorted, so the value under its marker is its smallest remaining one, and only these two values can come next. The smaller one is copied into an auxiliary array, and its marker moves on. On a tie the left value goes first. When one half runs out, the rest of the other follows without comparisons. Then the merged values are copied back. This is the two-pointer technique. Merging parts of p and q values makes at most p + q − 1 comparisons and at least as many as the smaller part has values.
Positions count from 0, as in the app. An odd number of values splits unevenly. Rounding the middle down gives the left part the extra value, so seven values split 4 + 3.
In pseudocode:
mergeSort(a, low, high)
if low >= high
return
mid = floor((low + high) / 2)
mergeSort(a, low, mid)
mergeSort(a, mid + 1, high)
merge(a, low, mid, high)
merge(a, low, mid, high)
i = low
j = mid + 1
k = 0
while i <= mid and j <= high
if a[i] <= a[j]
aux[k] = a[i]
i = i + 1
else
aux[k] = a[j]
j = j + 1
k = k + 1
for t from i to mid
aux[k] = a[t]
k = k + 1
for t from j to high
aux[k] = a[t]
k = k + 1
for t from 0 to high - low
a[low + t] = aux[t]
mergeSort stops when its part holds one value or none, when low >= high. In merge, i and j are the two markers and k is the next free cell of aux, one array of n cells made once. The test a[i] <= a[j] takes the left value on a tie. The next two loops copy the rest of whichever part is left, and the last copies aux back into a[low..high]. The first call is mergeSort(a, 0, n - 1).
The player sorts the left half, 8, 0, 5, 2, of the app's default array 8, 0, 5, 2, 3, 10, 1. It splits down to single values, then merges [8, 0] into [0, 8], [5, 2] into [2, 5], and those two into [0, 2, 5, 8]. In each merge the smaller front value moves down into the auxiliary array, and once one part is used up, the rest follows without a comparison.
The animation moves each value and leaves its cell empty; the code copies it.
The player sorts the right half, 3, 10, 1, which splits unevenly into [3, 10] and [1]; two merges give [1, 3, 10]. Each merge fills the auxiliary array from its first cell, so these values move down and left.
The final merge of 0, 2, 5, 8 and 1, 3, 10 makes six comparisons, the most a merge of four and three values can make. 10 follows without one, and the seven values go back: 0, 1, 2, 3, 5, 8, 10.
Yes. On a tie the merge takes the value from the left part, which came first, so equal values keep their original order; the example below shows a tie.
A merge writes its result while it still reads both parts, so writing into the array itself would overwrite values not yet merged. It collects the merged values in an auxiliary array of n cells instead and copies them back: O(n) extra space. The players show every copy into the auxiliary array and back.
The figure draws the sort as a recursion tree. Seven values need three levels of splits, about log2 n. Each level of merges copies its values into the auxiliary array and back once: O(n) per level, so O(n log n) in every case. The recurrence T(n) = 2T(n/2) + O(n) gives the same by the master theorem.
On the default array the three merge levels make 3, 4 and 6 comparisons and copy 6, 7 and 7 values each way, since 1 is alone at the lowest level. In all, six merges make 13 comparisons and 40 copies, and no swaps.
| Case | Comparisons | Seven values | Time | Extra space |
|---|---|---|---|---|
| Best | About (n/2) log2 n | 9 | O(n log n) | O(n) |
| Average | A little below the worst case | 12.7 | O(n log n) | O(n) |
| Worst | n⌈log2 n⌉ − 2⌈log2 n⌉ + 1 | 14 | O(n log n) | O(n) |
Every order of seven values makes the same 40 copies; only the comparisons vary. A sorted array is not the best case: it makes one comparison per left value in each merge, 11 in all. The reversed array makes one per right value, and the right part is never the larger: 9.
The auxiliary array of n values and the O(log n) recursion stack make O(n) extra space, not O(n log n): versions that copy the halves allocate more in all, but hold only O(n) at a time. So merge sort is not in-place. In-place merging exists, but it is complex or slower.
On a linked list, merging relinks nodes, so only the O(log n) stack is extra. Finding the middle takes a walk along the list, O(n) per level, so the sort stays O(n log n).
Note
Java's LinkedList has no sort of its own: List.sort copies it into an array, sorts that and writes the values back. C++'s std::list::sort merges by relinking nodes.
A stable sort keeps equal values in their original order. Merge sort is stable because a tie takes the left value, which came first. Merging [2a, 3] and [1, 2b], 1 goes first. 2a and 2b are equal, so 2a, the left one, goes next. Then come 2b and 3: 1, 2a, 2b, 3.
A strict "smaller than" test would take 2b first: still sorted, but not stable. The app's animation takes the left value, and only an array of your own with equal values shows its tie step.
Not in its basic form: it splits and merges the same way whatever the order, and in the app any seven values take 75 steps. Skipping a merge when the left part's last value is not larger than the right part's first makes sorted input O(n). Natural merge sort, and Timsort in Python and Java, merge runs that are already in order, so partly sorted data sorts faster.
On the array 8, 0, 5, 2, 3, 10, 1, merge sort makes 13 comparisons and 40 copies, insertion sort 16 comparisons and 11 shifts, and selection sort 21 comparisons and five swaps. On so few values the simple sorts do less work, so library sorts hand small parts to insertion sort.
| Property | Merge sort | Quick sort | Heap sort | Insertion sort |
|---|---|---|---|---|
| Average time | O(n log n) | O(n log n) | O(n log n) | O(n2) |
| Worst time | O(n log n) | O(n2) | O(n log n) | O(n2) |
| Extra space | O(n) | O(log n) stack on average | O(1) | O(1) |
| Stable | Yes | No | No | Yes |
Of the three O(n log n) sorts, quick sort is usually the fastest on data held in memory and heap sort the slowest. Merge sort pays O(n) memory for its guarantees. Merge sort vs quick sort: full comparison →
The app's version is top-down and recursive. Bottom-up merge sort is iterative: it merges single values into pairs, pairs into fours and so on, with no recursion stack. For seven values it makes the app's six merges, level by level.
The app shows the code in all three, linked to the full source on GitHub. It splits at (start + end) / 2, rounded down.
Note
In Java and C++, (start + end) / 2 can overflow int on arrays of over about a billion values; start + (end - start) / 2 avoids it. Python's integers do not overflow.
Python's list.sort() and sorted() and Java's sorts for objects use Timsort, a stable merge sort hybrid with temporary memory of at most n/2 items. C++'s std::stable_sort merges through a buffer, or in O(n log2 n) without one.
The full source code is on GitHub, in Python, Java and C++.
Merge sort suits:
For descending order, take the larger front value first, and still the left value on a tie.
// in the app
In VisiGrab merge sort runs on the default, a random or your own array of seven values, with a step for every split, min label and copy: 75 steps for any seven values.
Random picks seven distinct values from 0 to 19. Custom opens a seven-cell dialog for values from 0 to 99, equal ones included, with buttons for an ascending fill, which takes 11 comparisons, or a descending one, which takes 9. Equal values bring out the tie step.
Step forward and back through all 75 steps, every split, min label, copy and copy back with its message. Restart replays the array, and the last random or custom array comes back next time, shared with bubble, selection, insertion and quick sort.
One page: splitting down to single elements and merging back, out-of-place with O(n) auxiliary space, stable, not adaptive, O(n log n) in every case, and why merge sort suits external sorting.
The mergeSort, mergeSortRec and mergeBothParts methods in Java and merge_sort, merge_sort_rec and merge_both_parts in Python and C++, with links to the full source on GitHub. After the last step, a hint points to the code.
Eight questions with an explanation for every answer, from when the splitting stops to why a sorted array is no faster.
Bubble sort, selection sort, insertion sort, heap sort and quick sort each have a topic of their own.
// build your own
Download VisiGrab and step through every split, copy and merge, on the default array, a random one or an array of your own.
Merge sort is one of 30+ topics. See them all