If you have ever sorted a hand of playing cards, you already know Insertion Sort. You pick up one card at a time and slide it into the right place among the cards you are already holding.
It is one of the most useful simple sorting algorithms. It is fast on small or nearly sorted data, which is why real-world sorts like Timsort use it inside them.
By the end of this lesson, you will understand:
- How Insertion Sort works
- How to trace it by hand
- How to write it in code
- Why it can be as fast as
O(n) - When it is the best choice
What Is Insertion Sort?
Insertion Sort grows a sorted part on the left of the array, one value at a time:
- The first value on its own already counts as sorted.
- Take the next value. Call it the key.
- Move left through the sorted part. Every value bigger than the key shifts one place right to make room.
- When you reach a value that is not bigger, or the start of the array, drop the key into the gap.
- Repeat until every value has been inserted.
Watch it below. The key is lifted while it looks for its place, the light green values are the sorted part so far, and everything turns solid green once the whole array is done.
The Playing Cards Analogy
1. Start With One Card
Pick up the first card. A single card is already "sorted".
2. Pick Up the Next Card
Look at the new card. It needs to go somewhere among the cards you're holding.
3. Slide It Into Place
Compare it with the cards in your hand, from right to left. Every card bigger than it moves over a little to make space.
4. Repeat
Keep picking up cards and sliding each into place. Your hand is always sorted, and when the last card is in, you're done.
The important difference from Selection Sort: the sorted part is sorted, but values in it can still move when a smaller key arrives later. That's why it shows in light green, not solid green.
Tracing It by Hand
Let's sort [5, 1, 4, 2, 8] again.
Pass 1: insert 1
| Compare | Bigger than 1? | Array after |
|---|---|---|
| 5 and 1 | Yes, shift 5 right | [_, 5, 4, 2, 8] |
| start of array | Stop | [1, 5, 4, 2, 8] |
1 is the smallest so far, so it goes all the way to the front.
Pass 2: insert 4
| Compare | Bigger than 4? | Array after |
|---|---|---|
| 5 and 4 | Yes, shift 5 right | [1, _, 5, 2, 8] |
| 1 and 4 | No, stop | [1, 4, 5, 2, 8] |
Pass 3: insert 2
| Compare | Bigger than 2? | Array after |
|---|---|---|
| 5 and 2 | Yes, shift 5 right | [1, 4, _, 5, 8] |
| 4 and 2 | Yes, shift 4 right | [1, _, 4, 5, 8] |
| 1 and 2 | No, stop | [1, 2, 4, 5, 8] |
Pass 4: insert 8
| Compare | Bigger than 8? | Array after |
|---|---|---|
| 5 and 8 | No, stop | [1, 2, 4, 5, 8] |
8 is already bigger than everything before it, so it stays put after just one comparison.
The result is [1, 2, 4, 5, 8], in 7 comparisons and 4 shifts. The _ marks the gap left by shifting, where the key will eventually land.
Insertion Sort in Code
import java.util.Arrays;
public class Main {
static void insertionSort(int[] a) {
for (int i = 1; i < a.length; i++) {
int key = a[i]; // the value to insert
int j = i - 1;
while (j >= 0 && a[j] > key) { // shift bigger values one place right
a[j + 1] = a[j];
j--;
}
a[j + 1] = key; // drop the key into the gap
}
}
public static void main(String[] args) {
int[] marks = {5, 1, 4, 2, 8};
insertionSort(marks);
System.out.println(Arrays.toString(marks)); // [1, 2, 4, 5, 8]
}
}Let's connect the code to the trace:
- The outer loop starts at
i = 1, because the first value on its own is already sorted. keyis saved first, because shifting will overwritea[i].- The
whileloop is the "slide left" part: it keeps going while there are values left (j >= 0) and the value is bigger than the key. a[j + 1] = keydrops the key into the gap. When the loop stops,jis one place before the gap, so the key goes atj + 1.
How Fast Is Insertion Sort?
| Case | Example | Time | Why |
|---|---|---|---|
| Best | Already sorted | O(n) | Each key needs just one comparison, and nothing shifts |
| Average | Random order | O(n²) | Each key shifts past about half the sorted part |
| Worst | Reversed | O(n²) | Every key travels all the way to the front |
| Extra memory | Any | O(1) | Sorts in place, with just the key variable |
Try Sorted in the animation: 7 values take only 6 comparisons and no shifts at all. Then try Reversed: 21 comparisons and 21 shifts. That huge difference is what makes Insertion Sort adaptive: the more sorted the data already is, the faster it runs.
Insertion Sort is stable. It only shifts values that are strictly bigger than the key (
>), so a key never jumps past an equal value.
Common Mistakes
1. Checking the Value Before the Bounds
Write j >= 0 && a[j] > key, in that order. If you write a[j] > key && j >= 0, the code reads a[-1] when j reaches -1. In Java that stops the program with an error, and in C it is undefined behaviour. Python and JavaScript survive only by luck: Python's a[-1] quietly reads the last value, and JavaScript gives undefined. The && skips the second check only when the first one is false, so the bounds check must come first.
2. Forgetting to Save the Key
If you compare against a[i] directly instead of a saved key, the first shift overwrites it and the value is lost.
3. Putting the Key at j Instead of j + 1
When the loop ends, j points at the value that is not bigger than the key, or at -1. The gap is one place to the right, at j + 1.
When Should You Use Insertion Sort?
Good for:
- Small arrays: for a handful of values, it is often faster in practice than Merge Sort or Quick Sort
- Nearly sorted data, where it runs close to
O(n) - Data that arrives one value at a time, because it can insert each new value as it comes
Not good for:
- Large arrays in random order, where it is
O(n²)
This is why real-world sorting algorithms like Timsort use Insertion Sort for small pieces of the data, and a faster algorithm for the rest.
In the next lesson, we will move on to our first O(n log n) algorithm: Merge Sort.
Remember This
If you remember only one thing from this lesson, remember: Insertion Sort takes each value and slides it left into a growing sorted part, shifting bigger values right. It is O(n²) in general, but close to O(n) on nearly sorted data.