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, sort it into ascending order with merge sort. Equal values may appear more than once, and the array may be empty.

Example
Input: nums = [38, 27, 43, 3, 9, 82, 10]
Output: [3, 9, 10, 27, 38, 43, 82]
Solution

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] has no sorted piles in it, though. 38 comes before 27, and 43 before 3. So where would two sorted piles come from?

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.

Merge sort on 38, 27, 43, 3, 9, 82, 10. Three split rows halve the array down to single values. Three merge rows join them back: 27, 38 and 3, 43 and 9, 82 and 10, then 3, 27, 38, 43 and 9, 10, 82, then the sorted array.

Look at the three rows labelled split. The seven values become [38, 27, 43, 3] and [9, 82, 10], then four short pieces, then seven single values. The rows labelled merge go back up. 38 and 27 join as [27, 38], and 43 and 3 join as [3, 43]. In the dashed box, 9 and 82 are already in order, so that merge has nothing to do.

The orange row at the bottom joins [3, 27, 38, 43] with [9, 10, 82]. The front values are compared in turn: 3 against 9, then 27 against 9, 27 against 10, 27 against 82, 38 against 82 and 43 against 82. Each comparison places one value. Once the left piece is used up, 82 is the last value of the right piece, and it already sits at the end.

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 left to right. The middle position is mid = left + (right - left) / 2, so the halves are left to mid and mid + 1 to right. A range of one value stops the cutting.

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) / 2? With left at 1,500,000,000 and right at 1,600,000,000, the sum is too big for an int, and a test run printed -597,483,648. The form above printed 1,550,000,000. Such positions need an array of over 1.5 billion values, but the safe form is no harder to write.

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, 5a, 3b, 5c, 1d and 3e, by their number with the same merge. Taking the left value on ties gave [1d, 3b, 3e, 5a, 5c], with 3b still before 3e. Taking the right value on ties gave [1d, 3e, 3b, 5a, 5c], and the two 3s swapped.

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 works in these steps:

  1. First, return straight away if nums has fewer than two values. Otherwise create buffer, an array as long as nums, and call the helper mergeSort(nums, buffer, left, right), which sorts the range from left to right, on the whole array.
  2. In mergeSort, a range of one value returns at once. Any longer range gets its middle position mid, and mergeSort calls itself on left to mid and on mid + 1 to right.
  3. With both halves sorted, compare nums[mid] with nums[mid + 1]. If the left value is not bigger, the range is in order and mergeSort returns.
  4. Otherwise call merge. It copies the range into buffer with System.arraycopy and sets three markers: i at the start of the left half, j at the start of the right half, and k at the next position to fill in nums.
  5. A loop runs while both halves have values left. Each pass writes the smaller front value to nums[k], taking the left one on ties, and moves k and the marker it took from.
  6. 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 main method sorts the example, an empty array, one value, sorted and reversed input, repeats with negative numbers, and the largest and smallest int values.

Java
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:

Output
[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], the same as the orange row in the picture. The empty array and [7] come back unchanged, since sort returns before creating a buffer.

Look at the line for [4, -2, 4, 0, -2, 4]: the two -2s and the three 4s end up side by side, and the negatives come first. In the last line, -2147483648 moves to the front and 2147483647 to the end. The code only compares values with <= and never subtracts them, so there is no sum or difference that could go past the range of an int.

The original implementation, with JUnit tests, is on GitHub.

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 buffer is as long as the array, while the calls of mergeSort waiting for their halves add only about log2 n more.

The sort is stable but not in place. Java's own Arrays.sort for arrays of objects calls ComparableTimSort, which uses Timsort, a merge sort variant. For a sort that needs no buffer but can slow to O(n²) on unlucky input, see Quick Sort.