Post

Adaptive Merge Sort in Java

Learn how Adaptive 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.

Adaptive Merge Sort in Java

Introduction

Adaptive Merge Sort is a merge sort that takes advantage of order that is already in the data. A plain merge sort does the same work for every input: it splits the array down to single values and merges everything back up, even when the array is already sorted. An adaptive merge sort notices when parts of the array are already in order and skips the work for them.

Three ideas carry the whole algorithm:

  • Divide and conquer: split the range in half, sort both halves recursively, and merge them, as in Merge Sort.
  • The ordered-halves check: after both halves are sorted, a merge is only needed if the last value of the left half is larger than the first value of the right half. If it isn’t, the two halves together are already sorted, and one comparison replaces the whole merge.
  • Natural runs: more advanced adaptive sorts, such as natural merge sort and TimSort, go further and look for the sorted runs already present in the input, merging those instead of fixed halves.

Adaptivity matters because real data is rarely random: logs arrive almost in time order, lists are sorted and then slightly changed, records come from systems that already keep them in order. An adaptive sort turns that existing order into saved time; with the ordered-halves check, merge sort runs in linear time on sorted input.

This article uses top-down merge sort with a shared auxiliary array, and shows what the ordered-halves check adds. The Java code in the repository leaves that check out, so it isn’t actually adaptive; the Java section explains the difference.

Performance Characteristics

Merge sort always makes about $\log_2 n$ levels of merges; how much work each level does depends on whether the halves are already in order, and on whether the code checks.

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)$Sorted input with the ordered-halves check: every merge is skipped
Average$O(n \log n)$Random input: almost every merge is needed
Worst$O(n \log n)$Any input: the splits are always even

Why $n$ for sorted input? With the check, every call does one comparison between its two halves and returns, and a merge sort makes $n - 1$ such calls, so sorted input costs $n - 1$ comparisons. Without the check, each level still merges every value: the repository code makes 853,904 comparisons for 100,000 sorted values, against 99,999 with the check. On random input the check rarely succeeds and adds one comparison per call, about 4 % more.

The check pays off far beyond fully sorted data. Any range that happens to be in order, such as a sorted block inside otherwise random data, is skipped as a whole, at every level of the recursion.

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 auxiliary array, plus $O(\log n)$ for the recursion stack
In placeNo
StableYes (on a tie, the merge takes the value from the left half first)

Algorithm (Pseudo Code)

Adaptive Merge Sort splits the range in the middle, sorts the left half and the right half the same way, recursively, and then looks at the two values where the halves meet. If the last value of the left half is not larger than the first value of the right half, every value on the left is at most every value on the right, and since both halves are sorted, the whole range is already sorted. Nothing more needs to happen.

Otherwise the two halves are merged: they are copied into the auxiliary array, and the smaller front value is written back each time, until both halves are used up. As the recursion unwinds, larger and larger ranges become sorted, and the last merge, or skipped merge, sorts the whole array.

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
sort(array):
    aux = copy of array
    sort(array, aux, 0, n - 1)

sort(array, aux, low, high):
    if low >= high: return
    mid = low + (high - low) / 2
    sort(array, aux, low, mid)
    sort(array, aux, mid + 1, high)
    if array[mid] <= array[mid + 1]: return     // the adaptive check, missing from the Java code
    merge(array, aux, low, mid, high)

merge(array, aux, low, mid, high):
    copy array[low .. high] into aux[low .. high]
    i = low, j = mid + 1
    for k = low to high:
        take aux[i] or aux[j], whichever is smaller (aux[i] on a tie)

After sort(array, aux, low, high), the range array[low .. high] is sorted, whether the merge ran or was skipped.

The check compares array[mid] with array[mid + 1] after both halves have been sorted. Checking before the recursion would tell nothing, because the halves aren’t sorted yet.

Visualization

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

Each step shows one call that merges two sorted halves, or skips the merge, with the line of code that ran and a short explanation. The individual moves inside a merge are shown in the Merge Sort guide.

  • 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.
  • Range: values outside the range of the current call fade out, and the gray bar marks where the left half ends and the right half begins.
  • Colours: a range that was just merged is salmon, a range whose merge was skipped is amber, and the array turns green when it is sorted.
  • Adaptive check: tick Adaptive check to add the ordered-halves check that the Java code leaves out.
  • Sorted input: tick Sorted input to start from [0, 1, …, 9]. Compare the comparison counts with and without the check.
merged merge skipped sorted

Java Code

The implementation is an AdaptiveMergeSort class with one public method, sort, and two private methods: a recursive sort that splits and recurses, and merge, which merges two sorted halves through the auxiliary array. One small helper, less, lives in a separate SortUtils class.

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

sort

1
2
3
4
5
6
7
8
9
@SuppressWarnings("unchecked")
public <T extends Comparable<T>> T[] sort(T[] array) {
    if (array.length <= 1) {
        return array;
    }
    T[] aux = array.clone();
    sort(array, aux, 0, array.length - 1);
    return array;
}

The public sort returns arrays of zero or one value straight back. Otherwise it creates the auxiliary array once, as a clone of the input, which also gives it the right generic type without a cast, and starts the recursion on the whole range. The array is sorted in place and returned.

Unlike the repository’s MergeSort, which keeps its temporary array in an instance field, this class creates aux as a local variable and passes it down, so two threads can safely use the same AdaptiveMergeSort object at the same time.

sort (recursive)

1
2
3
4
5
6
7
8
9
private <T extends Comparable<T>> void sort(T[] array, T[] aux, int low, int high) {
    if (low >= high) {
        return;
    }
    int mid = low + (high - low) / 2;
    sort(array, aux, low, mid);
    sort(array, aux, mid + 1, high);
    merge(array, aux, low, mid, high);
}

The recursive sort handles array[low .. high]. A range of one value is already sorted. Otherwise it finds the middle with low + (high - low) / 2, which can’t overflow, sorts both halves, and merges them.

Despite the class name, this method is not adaptive: it always merges, even when the two halves are already in order, so sorted input does nearly as much work as random input. The repository code makes 853,904 comparisons for 100,000 sorted values and 1,536,500 for random ones. Adding one line before the merge, if (!SortUtils.less(array[mid + 1], array[mid])) { return; }, skips merges of ordered halves and brings sorted input down to 99,999 comparisons, for about 4 % extra on random input.

merge

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
private <T extends Comparable<T>> void merge(T[] array, T[] aux, int low, int mid, int high) {
    System.arraycopy(array, low, aux, low, high - low + 1);
    int i = low;
    int j = mid + 1;
    for (int k = low; k <= high; k++) {
        if (i > mid) {
            array[k] = aux[j++];
        } else if (j > high) {
            array[k] = aux[i++];
        } else if (SortUtils.less(aux[j], aux[i])) {
            array[k] = aux[j++];
        } else {
            array[k] = aux[i++];
        }
    }
}

merge copies the range into aux at the same indices and writes it back in sorted order: i walks the left half, j the right half, and each position k gets the smaller front value. The first two branches handle a half that is used up. The right value is only taken when it is strictly less, so on a tie the left value goes first, and the sort is stable.

less

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

This helper from SortUtils is the only comparison the class needs: less returns true when the first element is smaller than the second, 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 AdaptiveMergeSort().sort(numbers);
System.out.println(Arrays.toString(numbers));
// [0, 1, 2, 3, 4, 5, 6, 7, 8, 9]

Create an AdaptiveMergeSort, pass it an array, and the same array comes back sorted, after 23 comparisons. The same values in sorted order still take 19 comparisons with this code; with the adaptive check, they would take 9.

Summary

  • Adaptive Merge Sort is a merge sort that skips work on data that is already in order, most simply by checking whether two sorted halves are already in order before merging them.
  • This implementation is a top-down merge sort with one auxiliary array created per call to sort, which makes it safe to share between threads.
  • After each recursive call, its range is sorted, and the last call sorts the whole array.
  • With the ordered-halves check, it runs in $O(n)$ on sorted input and $O(n \log n)$ otherwise, needs $O(n)$ extra space, and is stable but not in place.
  • The Java code leaves the check out, so it behaves like plain merge sort. For real use, Arrays.sort() on object arrays runs TimSort, which adapts to existing runs even better.
This post is licensed under CC BY 4.0 by the author.