Merge Sort
Sort an array by cutting it into halves, sorting each half and merging the sorted halves back together.
Given an array of integers nums
Example
Output: [3, 9, 10, 27, 38, 43, 82]
The Idea
Picture two piles of exam papers, each already sorted by score with the lowest on top. Joining them into one sorted pile is easy. Look at the two top papers, move the lower one to the new pile, and repeat. You never need to look below the top paper of either pile.
The array [38, 27, 43, 3, 9, 82, 10]
Keep cutting. Cut the array in half, cut each half in half again, and stop when every piece holds one value. A piece with one value is sorted already, because there is nothing to put in order. From there, join neighbouring pieces with the top-paper rule, and every join produces a longer sorted piece.
Look at the three rows labelled split. The seven values become [38, 27, 43, 3][9, 82, 10][27, 38][3, 43]
The orange row at the bottom joins [3, 27, 38, 43][9, 10, 82]
Joining two sorted pieces by always taking the smaller front value is called merging, and sorting by repeated cutting and merging is merge sort. Halving the seven values, sorting each half the same way and combining the two results is an example of divide and conquer.
Solution Approach
Five questions shape the code: why halving beats a simpler sort, how the halves are found, how two halves are merged, where the merged values are stored, and, as an optional speed-up, when a merge can be skipped.
Why halving pays off
Why not a simpler sort? Insertion sort, for example, takes the values one by one and slides each into place among the ones before it. On an array in reverse order every new value passes all the earlier ones, which is about n²/2 comparisons for n values.
Merge sort cuts 1,024 values in half ten times before the pieces hold one value, so there are ten rows of merges. Each merge row compares at most one front value per value placed, so at most 1,024 comparisons per row. A test run on 1,024 random values (seed 42) made 9,654 comparisons in total.
Finding the halves
How does the code cut an array without making new arrays? It works on a range of positions, from leftrightmid = left + (right - left) / 2leftmidmid + 1right
How does each half get sorted? By the same method. In the picture, sorting positions 0 to 6 first sorts positions 0 to 3 and 4 to 6, each of those sorts its own two halves, and the last split row is where the ranges are down to one value. A method that sorts a range by calling itself on the two halves like this uses recursion.
Why not (left + right) / 2leftrightint
Merging two sorted halves
How are two sorted halves merged inside one array? Copy the range into a second array, the buffer, and read from there. One marker walks the left half, another the right half, and a third marks the next position to fill in the array. Each step writes the smaller of the two front values and moves its marker on.
What if the two front values are equal? The code takes the left one. That keeps equal values in the order they had, which makes the sort stable. With plain integers you cannot tell two 4s apart, but with records sorted by one field you can.
A test run sorted five cards, 5a3b5c1d3e[1d, 3b, 3e, 5a, 5c]3b3e[1d, 3e, 3b, 5a, 5c]
Where the merged values go
Does every merge need its own new arrays? A simple version creates two new arrays for the halves at every merge. Here one buffer, as long as the whole array, is created once and shared by all merges. Merge sort still needs that buffer, so it does not sort in place, meaning inside the original array alone.
Skipping merges that have nothing to do
Can a merge be left out altogether? Sometimes, and checking for it is an optional speed-up. After both halves are sorted, if the last value of the left half is no bigger than the first value of the right half, the range is already sorted. That is the dashed box in the picture: 9 is not bigger than 82. One comparison then replaces the whole merge, and on sorted input every merge is skipped.
Java Solution
The method sort
- First, return straight away if
has fewer than two values. Otherwise createnums , an array as long asbuffer , and call the helpernums , which sorts the range frommergeSort(nums, buffer, left, right) toleft , on the whole array.right - In
, a range of one value returns at once. Any longer range gets its middle positionmergeSort , andmid calls itself onmergeSort toleft and onmid tomid + 1 .right - With both halves sorted, compare
withnums[mid] . If the left value is not bigger, the range is in order andnums[mid + 1] returns.mergeSort - Otherwise call
. It copies the range intomerge withbuffer and sets three markers:System.arraycopy at the start of the left half,i at the start of the right half, andj at the next position to fill ink .nums - A loop runs while both halves have values left. Each pass writes the smaller front value to
, taking the left one on ties, and movesnums[k] and the marker it took from.k - A second loop copies what is left of the left half. Values left over in the right half need no copy, because they already sit at the end of the range in
.nums
The mainint
import java.util.Arrays;
public class MergeSort {
public static void sort(int[] nums) {
if (nums.length < 2) {
return;
}
int[] buffer = new int[nums.length]; // one shared buffer instead of new arrays per merge
mergeSort(nums, buffer, 0, nums.length - 1);
}
private static void mergeSort(int[] nums, int[] buffer, int left, int right) {
if (left >= right) {
return; // one value is already sorted
}
int mid = left + (right - left) / 2; // avoids overflow of (left + right)
mergeSort(nums, buffer, left, mid);
mergeSort(nums, buffer, mid + 1, right);
if (nums[mid] <= nums[mid + 1]) {
return; // halves are already in order
}
merge(nums, buffer, left, mid, right);
}
// Merges the sorted ranges nums[left..mid] and nums[mid+1..right]
private static void merge(int[] nums, int[] buffer, int left, int mid, int right) {
System.arraycopy(nums, left, buffer, left, right - left + 1);
int i = left; // next unused value in the left half
int j = mid + 1; // next unused value in the right half
int k = left; // next position to fill in nums
while (i <= mid && j <= right) {
// <= takes from the left half on ties, which keeps the sort stable
nums[k++] = (buffer[i] <= buffer[j]) ? buffer[i++] : buffer[j++];
}
while (i <= mid) {
nums[k++] = buffer[i++];
}
// any values left in the right half are already in place
}
public static void main(String[] args) {
int[][] tests = {
{38, 27, 43, 3, 9, 82, 10},
{},
{7},
{1, 2, 3, 4, 5},
{5, 4, 3, 2, 1},
{4, -2, 4, 0, -2, 4},
{Integer.MAX_VALUE, Integer.MIN_VALUE, 0}
};
for (int[] data : tests) {
String before = Arrays.toString(data);
sort(data);
System.out.println(before + " -> " + Arrays.toString(data));
}
}
}
Running it prints:
[38, 27, 43, 3, 9, 82, 10] -> [3, 9, 10, 27, 38, 43, 82]
[] -> []
[7] -> [7]
[1, 2, 3, 4, 5] -> [1, 2, 3, 4, 5]
[5, 4, 3, 2, 1] -> [1, 2, 3, 4, 5]
[4, -2, 4, 0, -2, 4] -> [-2, -2, 0, 4, 4, 4]
[2147483647, -2147483648, 0] -> [-2147483648, 0, 2147483647]
The example comes out as [3, 9, 10, 27, 38, 43, 82][7]sort
Look at the line for [4, -2, 4, 0, -2, 4]<=int
The original implementation, with JUnit tests, is on
Complexity
The cost comes from the rows of merges, and the skip check decides how many of them do real work.
- Best time: O(n), for input that is already sorted, because every merge is skipped after one comparison, and a test run on 1,024 sorted values did 0 merges and 1,023 comparisons.
- Average time: O(n log n), for input in random order, because there are about log2 n rows of merges and each row places all n values, and a test run on 1,024 random values (seed 42) made 9,654 comparisons.
- Worst time: O(n log n), for input such as reverse order, where no merge can be skipped (1,023 merges for 1,024 values in a test run) and every row copies all n values through the buffer.
- Space: O(n), because
is as long as the array, while the calls ofbuffer waiting for their halves add only about log2 n more.mergeSort
The sort is stable but not in place. Java's own Arrays.sortComparableTimSort