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
Output: [5, 6, 11, 12, 13]
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
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
Both checks sit in one loop condition, and their order matters. The check j >= 0
The comparison is a strict >
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.sortint
Java Solution
The method sort
- First, set a counter
to 0. Sorting does not need it; it letsshifts show how much work each array caused.main - An outer loop moves
from position 1 to the end of the array, becausei alone is the sorted part at the start. For eacharr[0] , savei inarr[i] .key - Inside, a second loop, a
loop, startswhile atj . Whilei - 1 andj >= 0 , it copiesarr[j] > key one place right intoarr[j] , movesarr[j + 1] left and adds one toj .shifts - When the
loop stops,while is the free cell, so writearr[j + 1] there.key - When the outer loop is done, the array is sorted, and the method returns
.shifts
A second method, sortPairs{value, position}show
The main{value, position}
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:
[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]
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]
The last line shows stability. Each pair holds a value and the position it started at. The two 26s come out as [26, 1][26, 3][41, 0][41, 2]>=>[[26, 3], [26, 1], [41, 2], [41, 0]]
The order of the two checks matters just as much. Written as arr[j] > key && j >= 0arr[-1]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
shifts alli values before it. That adds up to n(n - 1)/2 shifts, 499,500 for 1,000 values.i - Space: O(1), because the sort works inside the array and keeps only
,i ,j and the counter. It is an in-place sort, and the strictkey makes it stable.>
For large arrays in random order,