Post

Merge Sort in Java

Learn how Merge Sort works: its time and space complexity, the algorithm in pseudo code, and a step-by-step visualisation that follows the Java code line by line.

Merge Sort in Java

Introduction

Merge Sort is a divide-and-conquer sorting algorithm. It splits the array in half, sorts each half the same way, recursively, and then merges the two sorted halves into one sorted whole.

Three ideas carry the whole algorithm:

  • Split: cut the range in the middle until every part holds a single element, which is sorted by definition.
  • Merge: combine two sorted halves by repeatedly taking the smaller of their front values.
  • Temporary array: a second array that holds a copy of the two halves while they are merged back into the original.

Merge Sort always runs in $O(n \log n)$, whatever the input looks like, and it is stable: equal values keep their original order. That combination makes it the classic choice for sorting objects. Java’s Arrays.sort() for object arrays and Collections.sort() both use TimSort, a hybrid built on merge sort.

This article uses a top-down merge sort with one shared temporary array: the array is allocated once, and each merge copies only its own range into it.

Performance Characteristics

Merge Sort does the same amount of work for every input of a given size, so its speed is predictable, but it pays for that with extra memory for the temporary array.

Time Complexity

Time complexity describes how the number of steps an algorithm takes grows as the input gets larger.

CaseTimeWhen it happens
Best$O(n \log n)$Any input, including an array that is already sorted
Average$O(n \log n)$Random or mixed input
Worst$O(n \log n)$Any input: the splits are always even

Why $n \log n$ in every case? The split always cuts the range in the middle, so there are about $\log_2 n$ levels of recursion, and the merges on each level copy every element once ($n$ work). The input values never change the shape of the splits.

This implementation merges even when the two halves are already in order. Adding a check such as “skip the merge if arr[mid] is not larger than arr[mid + 1]” makes an already sorted array run in $O(n)$.

Space Complexity

Space complexity describes how much extra memory an algorithm needs, beyond the input itself, as the input gets larger.

PropertyValue
Space$O(n)$ for the temporary array, plus $O(\log n)$ for the recursion stack
In placeNo
StableYes (on a tie, the value from the left half is taken first)

Algorithm (Pseudo Code)

Merge Sort starts by splitting the array in the middle into a left half and a right half, and it keeps splitting each half until every part holds one value. A part with one value is already sorted. Then the parts are merged back together in pairs. To merge two sorted halves, it looks at the first value of each half, moves the smaller one into the next free position, and repeats. When one half runs out, the rest of the other half follows in order.

Each merge turns two small sorted parts into one bigger sorted part. The merges work their way back up through the splits: two single values become a sorted pair, two pairs become a sorted group of four, and so on, until the last merge joins the two halves of the whole array and everything is in order.

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
sort(array):
    tempArray = new array of the same length
    doSort(array, 0, length - 1)

doSort(arr, left, right):
    if left < right:
        mid = (left + right) / 2
        doSort(arr, left, mid)
        doSort(arr, mid + 1, right)
        merge(arr, left, mid, right)

merge(arr, left, mid, right):
    copy arr[left .. right] into tempArray[left .. right]
    i = left, j = mid + 1
    for k = left to right:
        if j > right:                         arr[k] = tempArray[i++]   // right half used up
        else if i > mid:                      arr[k] = tempArray[j++]   // left half used up
        else if tempArray[j] < tempArray[i]:  arr[k] = tempArray[j++]
        else:                                 arr[k] = tempArray[i++]

After merge returns, arr[left .. right] holds the same values as before, now in sorted order.

The comparison is strict: the right value is taken only when it is smaller than the left value. On a tie the left value wins, and that is exactly what makes Merge Sort stable.

Visualization

The visualization below follows the Java code line by line, starting with the values 0 to 9 in shuffled order.

Each step shows the array, the temporary array, the pointers and the line of code that is running, with a short explanation of what just happened:

  • Step through: use the arrows to move one step forward or back, or drag the slider to jump to any step.
  • Play: press Play to run the steps automatically, and press it again to pause.
  • Shuffle: press the shuffle button to start again with a new random order.
  • Pointers: I is i, the next value in the left half, and J is j, the next value in the right half, both in tempArray. K is k, the position in arr being written.
  • Colours: the value it is compared against is amber, the value being copied back is salmon, and values in a sorted run are green.
  • Split: the gray bar marks where the range is split, between mid and mid + 1.
  • Temp row: during a merge, the bottom row shows tempArray. Values that have already been copied back fade out.
compared copied back sorted run I = i J = j K = k

Java Code

The implementation is a MergeSort class with one public method, sort, and two private methods: doSort handles the splitting and recursion, and merge combines two sorted halves. The class keeps the temporary array in a field, tempArray. One small helper, less, lives in a separate SortUtils class.

The complete code is in the algorithm-examples repository on GitHub: MergeSort.java, with the helpers in SortUtils.java.

sort

1
2
3
4
5
6
@Override
public <T extends Comparable<T>> T[] sort(T[] unsorted) {
    tempArray = new Comparable[unsorted.length];
    doSort(unsorted, 0, unsorted.length - 1);
    return unsorted;
}

sort is the entry point. It accepts an array of any Comparable type, such as Integer or String, and creates the temporary array once, with the same length as the input. It then calls doSort on the full range, from index 0 to the last index, and returns the same array, now sorted. Despite the parameter name unsorted, the array is sorted in place and returned.

tempArray is an instance field, not a local variable. Two threads that call sort on the same MergeSort object at the same time share it and overwrite each other’s data. The field also keeps a reference to the elements of the last sorted array after sort returns. Creating the array in sort and passing it to doSort and merge as a parameter avoids both problems.

doSort

1
2
3
4
5
6
7
8
private <T extends Comparable<T>> void doSort(T[] arr, int left, int right) {
    if (left < right) {
        int mid = (left + right) >>> 1;
        doSort(arr, left, mid);
        doSort(arr, mid + 1, right);
        merge(arr, left, mid, right);
    }
}

doSort is the recursive part. When the range has fewer than two elements, it is already sorted and there is nothing to do. Otherwise it finds the middle, sorts the left half [left .. mid] and the right half [mid + 1 .. right] the same way, and then merges them.

(left + right) >>> 1 finds the middle with an unsigned shift, so it can’t overflow the way (left + right) / 2 can for very large indices.

merge

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
private <T extends Comparable<T>> void merge(T[] arr, int left, int mid, int right) {
    int i = left;
    int j = mid + 1;
    System.arraycopy(arr, left, tempArray, left, right + 1 - left);

    for (int k = left; k <= right; k++) {
        if (j > right) {
            arr[k] = (T) tempArray[i++];
        } else if (i > mid) {
            arr[k] = (T) tempArray[j++];
        } else if (less(tempArray[j], tempArray[i])) {
            arr[k] = (T) tempArray[j++];
        } else {
            arr[k] = (T) tempArray[i++];
        }
    }
}

merge does the real work. It copies the range [left .. right] into tempArray, at the same indices, so the two sorted halves are safe while arr is overwritten. Then k walks through arr from left to right, and each position gets the smaller of the two front values: tempArray[i] from the left half or tempArray[j] from the right half.

Two details are worth noticing:

  • The first two branches handle a half that is used up. Once j passes right, only left values remain, and once i passes mid, only right values remain. They are checked first so tempArray[i] and tempArray[j] are never read past the end of their half.
  • The right value is taken only when it is strictly less than the left value. On a tie, the left value goes first, which keeps equal elements in their original order and makes the sort stable.

tempArray is a raw Comparable[], because Java can’t create a generic T[] directly, so every value read from it needs the (T) cast. That is why the class carries @SuppressWarnings("rawtypes") and merge carries @SuppressWarnings("unchecked").

less

1
2
3
static <T extends Comparable<T>> boolean less(T a, T b) {
    return a.compareTo(b) < 0;
}

This helper from SortUtils keeps merge easy to read. less returns true when a is smaller than b, using compareTo, so the algorithm works for any type that implements Comparable.

Running it

1
2
3
4
Integer[] numbers = {7, 2, 9, 4, 0, 8, 3, 6, 1, 5};
new MergeSort().sort(numbers);
System.out.println(Arrays.toString(numbers));
// [0, 1, 2, 3, 4, 5, 6, 7, 8, 9]

Create a MergeSort, pass it an array, and the same array comes back sorted. The array holds Integer, not int, because the method works with Comparable objects.

Summary

  • Merge Sort is a divide-and-conquer sort: split the range in half, sort both halves recursively, then merge them.
  • This implementation is top-down: it splits at the middle until each range holds one element, and merges through one shared temporary array that is allocated once.
  • After each merge, the range [left .. right] is sorted, and the last merge sorts the whole array.
  • It runs in $O(n \log n)$ in the best, average and worst case, and needs $O(n)$ extra space for the temporary array.
  • It is stable but not in place. When memory is tight and stability doesn’t matter, an in-place sort such as QuickSort or heap sort is the better fit; Java’s Arrays.sort() uses a dual-pivot QuickSort for primitive arrays.
This post is licensed under CC BY 4.0 by the author.