Post

Insertion Sort in Java

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

Insertion Sort in Java

Introduction

Insertion Sort is a simple comparison sort that builds the sorted result one element at a time. It takes the next value from the unsorted part, and inserts it into its place in the sorted part on the left, the way most people sort a hand of playing cards.

Three ideas carry the whole algorithm:

  • Sorted part: the values to the left of i are always in sorted order. At the start, that is just the first value.
  • Key: the next value to insert, taken out of the array at position i.
  • Shift: every value in the sorted part that is larger than the key moves one position to the right, opening a gap where the key belongs.

Insertion Sort is $O(n^2)$ in general, but it is very fast on small arrays and on arrays that are already nearly sorted. That is why it lives inside many hybrid sorts: Java’s dual-pivot QuickSort switches to insertion sort for very small ranges, and TimSort uses a binary insertion sort to build its short runs.

This article uses the standard Insertion Sort that shifts instead of swapping: the key is held in a variable while larger values move right, and it is written into the gap once. The same class also has a sentinel variant, covered in the Java Code section.

Performance Characteristics

Insertion Sort needs almost no extra memory, and its speed depends on how sorted the input already is: each value only moves past the larger values in front of it.

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)$The array is already sorted: every key is compared once and stays
Average$O(n^2)$Random or mixed input
Worst$O(n^2)$The array is in reverse order: every key moves to the front

Why $n^2$? Each key moves past every larger value to its left, so the total number of shifts equals the number of pairs that are in the wrong order. A random array has about $\frac{n^2}{4}$ such pairs, and a reversed one has $\frac{n(n-1)}{2}$.

Because the work depends on how many values are out of place, Insertion Sort is adaptive: an array where every value is at most a few positions from its final place sorts in close to $O(n)$. That makes it a good choice for small or nearly sorted inputs.

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)$: only the key and two loop variables
In placeYes
StableYes (the key stops in front of an equal value, never past it)

Algorithm (Pseudo Code)

Insertion Sort starts with the second value, because a single value on its own is already sorted. It takes that value out of the array and holds it as the key. Then it looks at the sorted values to the left, from right to left: every value larger than the key moves one position to the right. As soon as it finds a value that is not larger, or reaches the start of the array, it stops and puts the key in the gap.

Now the first two values are sorted, and the next value becomes the key. Each round adds one more value to the sorted part on the left, and the unsorted part on the right gets one shorter. When the last value has been inserted, the whole array is sorted.

1
2
3
4
5
6
7
8
9
sort(items, start, end):                // end is exclusive
    for i = start + 1 to end - 1:
        key = items[i]
        j = i - 1
        while j >= start and key < items[j]:
            items[j + 1] = items[j]          // shift right
            j = j - 1
        items[j + 1] = key                   // insert into the gap
    return items

After each round of the outer loop, items[start .. i] holds the values that were originally there, now in sorted order.

Insertion Sort doesn’t swap: it shifts. Each larger value is copied one position to the right, and the key is written only once, at the end. A swap-based version does the same moves but writes the key on every step, which is about three times as many writes.

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 key above the gap it may go into, 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 position the key was taken from, and J is j, the value the key is compared with.
  • Colours: the key and the value it is compared with are amber, a value being shifted or the key being inserted is salmon, and the sorted part on the left is green.
  • Gap: the dashed cell is the gap where the key will go if it stops now. In the Java array, that cell still holds a copy of the value that just moved.
  • Boundary: the gray bar marks where the unsorted part starts.
key / compared shift / insert sorted part I = i J = j

Java Code

The implementation is an InsertionSort class with three public methods and one private helper: sort(array) is the entry point, sort(items, startIndex, endIndex) does the work on any range of the array, sentinelSort is an alternative version that starts by moving the smallest value to the front, and findMinIndex finds that smallest value. Two small helpers, less and swap, live in a separate SortUtils class.

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

sort

1
2
3
4
@Override
public <T extends Comparable<T>> T[] sort(T[] array) {
    return sort(array, 0, array.length);
}

sort is the entry point. It accepts an array of any Comparable type, such as Integer or String, and hands the whole array, from index 0 up to array.length, to the range version of sort. It returns the same array, now sorted.

sort with a range

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
public <T extends Comparable<T>> T[] sort(T[] items, final int startIndex, final int endIndex) {
    if (items == null || startIndex >= endIndex) {
        return items;
    }

    for (int i = startIndex + 1; i < endIndex; i++) {
        final T key = items[i];
        int j = i - 1;
        while (j >= startIndex && SortUtils.less(key, items[j])) {
            items[j + 1] = items[j];
            j--;
        }
        items[j + 1] = key;
    }

    return items;
}

This overload does the real work, on the range from startIndex up to, but not including, endIndex. An empty range, or a null array, is returned as it is. The outer loop takes each value from startIndex + 1 onwards as the key. The inner loop walks j back through the sorted part and shifts every value that is larger than the key one position to the right. When it stops, j + 1 is the gap, and the key is written there.

Two details are worth noticing:

  • j >= startIndex is checked before less, so items[j] is never read once j has passed the start of the range. When the key is smaller than everything in the sorted part, j ends at startIndex - 1 and the key goes to startIndex.
  • Sorting only part of an array is what hybrid sorts need: they split the work into small ranges and hand each one to insertion sort.

The items == null check never protects the one-argument sort: it reads array.length first, so sort(null) throws a NullPointerException before the range version is called. Only a direct call to sort(null, 0, 0) reaches the check.

sentinelSort

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
public <T extends Comparable<T>> T[] sentinelSort(T[] array) {
    if (array == null || array.length <= 1) {
        return array;
    }

    final int minElemIndex = findMinIndex(array);
    SortUtils.swap(array, 0, minElemIndex);

    for (int i = 2; i < array.length; i++) {
        final T currentValue = array[i];
        int j = i;
        while (j > 0 && SortUtils.less(currentValue, array[j - 1])) {
            array[j] = array[j - 1];
            j--;
        }
        array[j] = currentValue;
    }

    return array;
}

sentinelSort is a variant that first swaps the smallest value to index 0. That value acts as a sentinel: no key can ever be smaller than it, so the inner loop is guaranteed to stop at index 1 at the latest. With the smallest value in front, the first two positions are already sorted, which is why the outer loop starts at i = 2. Here j points at the gap rather than at the value being compared, so the loop compares with array[j - 1].

The Javadoc says the sentinel lets the loop avoid the j > 0 check, but the loop still checks j > 0 on every step, so the extra pass to find the minimum buys nothing. Dropping j > 0 && from the while condition gives the real sentinel version. Also, swapping the smallest value to the front can jump it over equal values, so unlike sort, sentinelSort is not stable.

findMinIndex

1
2
3
4
5
6
7
8
9
private <T extends Comparable<T>> int findMinIndex(final T[] array) {
    int minIndex = 0;
    for (int i = 1; i < array.length; i++) {
        if (SortUtils.less(array[i], array[minIndex])) {
            minIndex = i;
        }
    }
    return minIndex;
}

findMinIndex walks the whole array once and returns the index of the smallest value. Because the comparison is strict, it returns the first occurrence when the smallest value appears more than once.

less and swap

1
2
3
4
5
6
7
8
9
10
11
public static <T extends Comparable<T>> boolean less(T firstElement, T secondElement) {
    return firstElement.compareTo(secondElement) < 0;
}

public static <T> void swap(T[] array, int i, int j) {
    if (i != j) {
        final T temp = array[i];
        array[i] = array[j];
        array[j] = temp;
    }
}

These two helpers from SortUtils keep the sorting code 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 a strict comparison, the key stops in front of an equal value, which keeps sort stable. swap exchanges two elements, and is only used by sentinelSort.

Running it

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

Create an InsertionSort, pass it an array, and the same array comes back sorted. The array holds Integer, not int, because the method works with Comparable objects. To sort only part of an array, call sort(numbers, 2, 7) instead, which sorts indices 2 to 6 and leaves the rest alone.

Summary

  • Insertion Sort is a simple comparison sort that grows a sorted part on the left by inserting one key at a time.
  • This implementation shifts larger values one position right and writes the key into the gap once, and it can sort any range of an array.
  • After each round, items[start .. i] is sorted; after the last round, the whole range is.
  • It runs in $O(n)$ on sorted input and $O(n^2)$ on average and in the worst case, with only $O(1)$ extra space.
  • It is stable and sorts in place, and it is the best simple sort for small or nearly sorted inputs. For larger inputs, use an $O(n \log n)$ sort such as Merge Sort or QuickSort; their library versions often hand their smallest ranges to insertion sort.
This post is licensed under CC BY 4.0 by the author.