Insertion Sort

Sort an array by putting each value into the sorted part on its left, shifting larger values out of the way.

Given an array of integers, sort it into increasing order with insertion sort. Sort the array itself, without building a second array, and keep repeated values in the order they started in.

Example
Input: [12, 11, 13, 5, 6]
Output: [5, 6, 11, 12, 13]
Solution

The Idea

Think of being dealt playing cards one at a time and keeping your hand in order as they come. Each new card goes on the right end of your hand, and you slide it left past every card that is bigger, until a smaller card stops it.

Deal the example that way: 12, 11, 13, 5, 6. The first card, 12, is a hand of one, already in order. Next comes 11, smaller than 12, so it slides in front: 11, 12. Then 13 is bigger than 12 and stays where it lands. The 5 slides past 13, 12 and 11 to the front, and the 6 slides past the same three cards and stops behind the 5.

In a hand, a card slips easily between two others. An array has no room between its cells, though. So how do we open a gap at the right place?

We lift the new value out of its cell and keep it aside; the code calls it the key. Its cell is now free. Each bigger value to the left of the free cell moves one cell to the right, and the free cell moves one place left each time. When a value that is not bigger turns up, the key drops into the free cell.

The picture below runs the whole example. Each row shows the array after one step, and i is the position the key was lifted from.

Insertion sort on 12, 11, 13, 5, 6, one row per step. Key 11 moves before 12. Key 13 stays. Key 5 moves to position 0 after 13, 12 and 11 shift right. Key 6 moves to position 1 after 13, 12 and 11 shift right, giving 5, 6, 11, 12, 13.

In the row labelled "start", the teal cell holds 12 alone: that is the sorted part. Look at the row labelled "i = 3, key 5". The blue cells 11, 12 and 13 each moved one place right, and the orange arrow shows the 5 going from position 3 to position 0. In the row labelled "i = 2, key 13", nothing is blue: one look at 12 was enough.

So the array always has a sorted part on the left that grows by one value per step. Each step puts one more value into its place in that part, which is where the name insertion sort comes from.

Solution Approach

Three things need settling: how to move the bigger values out of the key's way, when to stop moving them, and how much work different arrays cause.

Shifting instead of swapping

Why not swap the key with its left neighbour, again and again, until it is in place? That sorts correctly too. But a swap in Java takes three assignments through a temporary variable. Holding the key aside means each bigger value is copied once, one place right, and the key is written once at the end.

Where shifting stops

When should the shifting stop? A marker j starts just left of the key and walks left. It stops at the first value that is not bigger than the key, or when it runs off the start of the array, as it does for the 5 in the example.

Both checks sit in one loop condition, and their order matters. The check j >= 0 has to come first, so the array is never read at position -1.

The comparison is a strict >, so shifting also stops at a value equal to the key. Picture two cards both showing 41, one dealt before the other. The later one stops behind the earlier one, so equal values keep the order they started in. A sort that keeps that order is called stable.

How much work different arrays cause

How long does all the shifting take? Each shift fixes exactly one pair of values that were in the wrong order. In the example, 12 sits before 11, 5 and 6, then 11 before 5 and 6, and 13 before 5 and 6. Those are 7 pairs, so the sort makes 7 shifts.

An array that is already sorted has no such pairs. Each key is compared once with its left neighbour and stays put. An array in reverse order has every pair wrong, so every key shifts all the way to the front.

Few out-of-order pairs mean little work, and a short stretch can only hold a few pairs. Library sorts make use of that: in JDK 25, Arrays.sort on an int array hands short parts to an insertion sort, for example a part at the left end of the array that is shorter than 44 values.

Java Solution

The method sort works in these steps:

  1. First, set a counter shifts to 0. Sorting does not need it; it lets main show how much work each array caused.
  2. An outer loop moves i from position 1 to the end of the array, because arr[0] alone is the sorted part at the start. For each i, save arr[i] in key.
  3. Inside, a second loop, a while loop, starts j at i - 1. While j >= 0 and arr[j] > key, it copies arr[j] one place right into arr[j + 1], moves j left and adds one to shifts.
  4. When the while loop stops, arr[j + 1] is the free cell, so write key there.
  5. When the outer loop is done, the array is sorted, and the method returns shifts.

A second method, sortPairs, runs the same two loops on {value, position} pairs and compares only the value, so the output can show what happens to equal values. A helper, show, sorts an array and prints it with its number of shifts.

The main method sorts the example, a sorted array, a reversed array, an array with repeats and negative numbers, one value, an empty array, and four {value, position} pairs that hold two 26s and two 41s.

Java
import java.util.Arrays;

public class InsertionSort {

    // Sorts arr in place and returns how many values were shifted right.
    public static int sort(int[] arr) {
        int shifts = 0;
        for (int i = 1; i < arr.length; i++) {
            int key = arr[i];                    // the value to insert into arr[0..i-1]
            int j = i - 1;
            while (j >= 0 && arr[j] > key) {   // strict >: stop at an equal value
                arr[j + 1] = arr[j];             // shift the larger value one place right
                j--;
                shifts++;
            }
            arr[j + 1] = key;                    // drop the key into the gap
        }
        return shifts;
    }

    // The same loop on {value, position} pairs, comparing only the value.
    public static void sortPairs(int[][] pairs) {
        for (int i = 1; i < pairs.length; i++) {
            int[] key = pairs[i];
            int j = i - 1;
            while (j >= 0 && pairs[j][0] > key[0]) {
                pairs[j + 1] = pairs[j];
                j--;
            }
            pairs[j + 1] = key;
        }
    }

    static void show(int[] arr) {
        int shifts = sort(arr);
        System.out.println(Arrays.toString(arr) + "  shifts: " + shifts);
    }

    public static void main(String[] args) {
        show(new int[] {12, 11, 13, 5, 6});
        show(new int[] {1, 2, 3, 4, 5, 6, 7, 8});          // already sorted
        show(new int[] {8, 7, 6, 5, 4, 3, 2, 1});          // reverse order
        show(new int[] {4, -2, 4, 0, -2});                 // repeats and negatives
        show(new int[] {7});
        show(new int[] {});

        int[][] pairs = {{41, 0}, {26, 1}, {41, 2}, {26, 3}};
        sortPairs(pairs);
        System.out.println(Arrays.deepToString(pairs));
    }
}

Running it prints:

Output
[5, 6, 11, 12, 13]  shifts: 7
[1, 2, 3, 4, 5, 6, 7, 8]  shifts: 0
[1, 2, 3, 4, 5, 6, 7, 8]  shifts: 28
[-2, -2, 0, 4, 4]  shifts: 6
[7]  shifts: 0
[]  shifts: 0
[[26, 1], [26, 3], [41, 0], [41, 2]]

The example comes out as [5, 6, 11, 12, 13] after 7 shifts: 1 in the row labelled "i = 1, key 11", none for 13, and 3 each for 5 and 6. Each shift fixed one of the 7 out-of-order pairs, such as 12 sitting before 11.

Both arrays of 1 to 8 end the same, but the sorted one cost 0 shifts and the reversed one 28. That is every one of the 8 × 7 / 2 = 28 pairs, each fixed by its own shift. The array [4, -2, 4, 0, -2] has 6 out-of-order pairs, and negative numbers need nothing special. With one value or none, the outer loop never runs, since it starts at position 1.

The last line shows stability. Each pair holds a value and the position it started at. The two 26s come out as [26, 1] then [26, 3], and the two 41s as [41, 0] then [41, 2], in their starting order. With >= in place of >, a key also slides past equal values, and that line becomes [[26, 3], [26, 1], [41, 2], [41, 0]].

The order of the two checks matters just as much. Written as arr[j] > key && j >= 0, the loop reads arr[-1] once 11 has passed 12. On the example, that throws ArrayIndexOutOfBoundsException: Index -1 out of bounds for length 5.

Complexity

For an array of n values, the cost is one comparison per key to find where it stops, plus one step for every shift, and the shifts equal the number of out-of-order pairs.

  • Best time: O(n), for an array that is already sorted, because each of the n - 1 keys is compared once with its left neighbour and never moves. For 1,000 sorted values that is 999 comparisons.
  • Average time: O(n²), for values in random order, because each key passes about half of the sorted part. Over 100 random arrays of 1,000 values, made with the fixed seed 42, the shifts averaged 249,577, close to n(n - 1)/4 = 249,750.
  • Worst time: O(n²), for an array in reverse order, because the key at position i shifts all i values before it. That adds up to n(n - 1)/2 shifts, 499,500 for 1,000 values.
  • Space: O(1), because the sort works inside the array and keeps only i, j, key and the counter. It is an in-place sort, and the strict > makes it stable.

For large arrays in random order, Merge Sort stays at O(n log n) and is also stable, at the cost of a second array.