Post

Binary Insertion Sort in Java

Learn how Binary Insertion 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.

Binary Insertion Sort in Java

Introduction

Binary Insertion Sort is a comparison sort and a variant of insertion sort. Like insertion sort, it takes the values one by one and inserts each into the sorted part on the left. The difference is how it finds the place: instead of comparing backwards one value at a time, it uses a binary search on the sorted part.

Three ideas carry the whole algorithm:

  • Sorted part: the values to the left of i are always sorted, so each new value only has to be inserted into them.
  • Binary search: to find where temp belongs, compare it with the middle of the sorted part, throw away the half it can’t be in, and repeat. That takes about $\log_2 i$ comparisons instead of up to $i$.
  • Shift: once the place is known, every value from there to i - 1 moves one position right to make room, exactly as in insertion sort.

Binary Insertion Sort is useful when comparisons are expensive, for example when comparing long strings or complex objects, because it cuts their number from $O(n^2)$ to $O(n \log n)$. It is used inside real sorting libraries: TimSort, Java’s sort for object arrays, uses a binary insertion sort to build its short runs. The Insertion Sort guide explains the plain version.

This article uses Binary Insertion Sort with a right-leaning binary search: equal values are inserted after each other, which keeps the sort stable.

Performance Characteristics

The binary search cuts the comparisons, but every insertion still has to shift values one by one, so the total time depends on how far the values have to move.

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)$An already sorted array: no shifts, but every binary search still runs
Average$O(n^2)$Random input: about $n^2 / 4$ shifts, but only $O(n \log n)$ comparisons
Worst$O(n^2)$A reverse-sorted array: every value shifts all the way to the front

Why still $n^2$? The binary search finds the place of each value in $O(\log n)$ comparisons, so all searches together cost $O(n \log n)$ comparisons. But inserting the value means shifting every larger value one position, and on average that is half the sorted part, so the moves still add up to $O(n^2)$. On the visualization’s starting data, Binary Insertion Sort makes 22 comparisons where plain insertion sort makes 33; the number of shifts is the same.

Plain insertion sort is $O(n)$ on an already sorted array, because it stops after one comparison per value. Binary Insertion Sort always runs the full binary search, so on sorted input it is slower: $O(n \log n)$. It pays off when comparisons are costly and the data is not nearly sorted.

Space Complexity

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

PropertyValue
Space$O(1)$: temp and a few indices
In placeYes
StableYes (on a tie, the search moves right, so temp goes after equal values)

Algorithm (Pseudo Code)

Binary Insertion Sort starts with the second value. It takes the value out as temp and searches the sorted part to its left. The search looks at the middle value of the range: if temp is smaller, its place is in the left half; otherwise it is in the right half. The range halves with every comparison, until it is empty, and then low is the index where temp belongs.

Every value from low up to the old position of temp then moves one place right, and temp is written into the free position. The sorted part has grown by one. The same steps repeat for every value up to the end of the array, and when the last value has been inserted, the whole array is sorted.

1
2
3
4
5
6
7
8
9
10
11
12
sort(array):
    for i = 1 to n - 1:
        temp = array[i]
        low = 0, high = i - 1
        while low <= high:
            mid = (low + high) / 2
            if temp < array[mid]: high = mid - 1
            else:                 low = mid + 1
        for j = i down to low + 1:
            array[j] = array[j - 1]
        array[low] = temp
    return array

After each round, array[0 .. i] holds the first i + 1 values in sorted order.

When the search ends, low is the first position whose value is larger than temp, or i if there is none. Values equal to temp send the search right, so temp lands after them, and equal values keep their original order.

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, temp above the gap it came from or is moving to, the search 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: L is low and H is high, the ends of the search range, and M is mid, the value being compared. Values in the sorted part outside the search range fade out.
  • Colours: temp and the value it is compared with are amber, a value being shifted or temp being inserted is salmon, and the sorted part on the left is green.
  • Insertion point: the gray bar marks low, where temp will be inserted, once the search is over. The dashed cell is the free position that moves left as values shift.
  • Comparisons: the footer counts the comparisons made so far.
temp / compared shift / insert sorted part L = low M = mid H = high

Java Code

The implementation is a BinaryInsertionSort class with a single method, sort, which does the binary search, the shifting and the insertion in one loop. One small helper, less, lives in a separate SortUtils class.

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

sort

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
public <T extends Comparable<T>> T[] sort(T[] array) {
    for (int i = 1; i < array.length; i++) {
        final T temp = array[i];
        int low = 0;
        int high = i - 1;

        while (low <= high) {
            final int mid = (low + high) >>> 1;
            if (SortUtils.less(temp, array[mid])) {
                high = mid - 1;
            } else {
                low = mid + 1;
            }
        }

        for (int j = i; j >= low + 1; j--) {
            array[j] = array[j - 1];
        }

        array[low] = temp;
    }
    return array;
}

sort accepts an array of any Comparable type and sorts it in place. The outer loop takes each value from index 1 onwards as temp. The while loop is a binary search over the sorted part [0 .. i - 1]: mid is the middle of the range, and depending on whether temp is smaller than array[mid], either high or low moves past mid. When the range is empty, low is where temp belongs. The for loop then shifts array[low .. i - 1] one position right, overwriting array[i], which is safe because its value is kept in temp, and temp is written to array[low].

Two details are worth noticing:

  • (low + high) >>> 1 finds the middle with an unsigned shift, so it can’t overflow the way (low + high) / 2 can for very large indices.
  • The shifting loop moves one element at a time. System.arraycopy(array, low, array, low + 1, i - low) does the same in a single call, and is usually faster for long shifts, but the number of moves stays the same.

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 keeps the binary search easy to read. less returns true when the first element is smaller than the second, using compareTo, so the algorithm works for any type that implements Comparable. Because it is strict, an equal value sends the search to the right half.

Running it

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

Create a BinaryInsertionSort, 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

  • Binary Insertion Sort is an insertion sort that finds each insertion point with a binary search on the sorted part.
  • This implementation searches with low, high and mid, shifts the larger values one place right, and inserts temp at low.
  • After each round, array[0 .. i] is sorted, and equal values keep their order because ties send the search to the right.
  • It makes only $O(n \log n)$ comparisons, but still $O(n^2)$ moves, so it runs in $O(n^2)$ time with $O(1)$ extra space, and is stable and in place.
  • Choose it over plain insertion sort when comparisons are expensive. For large arrays, use an $O(n \log n)$ sort such as merge sort, or Arrays.sort(), whose TimSort for object arrays uses binary insertion sort for its small runs.
This post is licensed under CC BY 4.0 by the author.