In a card game, your cards come one at a time. Each time you get a new card, you don't rearrange the whole hand. You shift the cards that are bigger than the new card a little to the right, then slide the new card into the gap that opens. So the cards in your hand are always sorted.
Insertion sort sorts an array the same way. The left part of the array is the cards in your hand, and it is always sorted. The next number to its right is the new card. One pass takes that number and slides it into the left part.
How it works
Sort [5, 2, 4, 6, 1, 3]. At the start, the sorted left part holds only the first number, 5. Pass 1 takes the second number, pass 2 takes the third, and so on.
| Pass | What happens | Array afterwards |
|---|---|---|
| 1 | take 2: shift 5, then 2 goes in at the front | [2, 5, 4, 6, 1, 3] |
| 2 | take 4: shift 5, stop at 2 | [2, 4, 5, 6, 1, 3] |
| 3 | take 6: 5 isn't bigger, 6 stays | [2, 4, 5, 6, 1, 3] |
| 4 | take 1: shift 6, 5, 4 and 2, then 1 goes in at the front | [1, 2, 4, 5, 6, 3] |
| 5 | take 3: shift 6, 5 and 4, stop at 2 | [1, 2, 3, 4, 5, 6] |
Here is insertion sort in JavaScript:
function insertionSort(arr) {
for (let i = 1; i < arr.length; i++) {
const current = arr[i]; // the number taken, like a card
let j = i - 1;
// shift the bigger ones right
while (j >= 0 && arr[j] > current) {
arr[j + 1] = arr[j];
j--;
}
arr[j + 1] = current; // insert
}
return arr;
}
console.log(insertionSort([5, 2, 4, 6, 1, 3]).join(",")); // 1,2,3,4,5,6
iis the index of the number taken. Theforloop starts ati = 1, because the number at index 0 has no number on its left.currentholds the number you've taken. The first shift overwritesarr[i]with the number on its left, so the number you took must be saved first.jstarts ati - 1and moves back through the left part, one place at a time. As long asarr[j]is bigger thancurrent,arr[j]shifts one place to the right (arr[j + 1] = arr[j]).j >= 0stops the loop at the left end of the array.- When the
whileloop stops, the gap is atj + 1, andcurrentgoes there.
Unlike bubble sort, insertion sort shifts instead of swapping. The bigger numbers move one place to the right, and current is only written once, at the end of the pass.
How fast it is
The amount of data is called n. How much work insertion sort does depends on the starting order of the data:
- Reversed data (the worst case) and shuffled data: reversed data is in order from big to small. Each number you take has to move a long way left. That's O(n²): double the data, and the time roughly quadruples.
- Sorted or nearly sorted data (the best case): each number, or almost each one, needs only one comparison with the number on its left. That number isn't bigger, so the
whileloop stops right away. That's O(n): double the data, double the time. For example, 1,000 numbers that are sorted except for two side-by-side numbers that are swapped need only about 1,000 comparisons. 1,000 reversed numbers need about 500,000.
Insertion sort's overhead is small too. Overhead is the extra work on top of comparing and shifting. Insertion sort needs no new array or extra memory, and its code is short. That's why insertion sort is often picked for small data (a few dozen items) and for nearly sorted data. JavaScript's built-in sort in Chrome and Node.js uses Timsort, and Timsort also uses insertion sort for short pieces of the data.
⚠️ When insertion sort goes wrong, and when it's slow
- Starting at
i = 0. The first number has no number on its left. Start ati = 1. - Not saving
current. If thewhileloop usesarr[j] > arr[i], the value ofarr[i]has already been overwritten by the first shift, so the result is a mess. Save the number first withconst current = arr[i]. - Inserting at
j. After thewhileloop,jpoints at a number that isn't bigger thancurrent, or it is-1(past the left end). The gap is atj + 1. - Big shuffled data. 100,000 shuffled numbers can take about 2.5 billion steps. For data like that, use JavaScript's built-in sort,
arr.sort((a, b) => a - b).
🎯 Bubble, selection or insertion?
| Bubble sort | Selection sort | Insertion sort | |
|---|---|---|---|
| Each pass | swaps two side-by-side numbers that are out of order | finds the smallest, swaps once | slides one number into the sorted left part |
| Already sorted data | O(n) with swapped |
still O(n²) | O(n) |
| Number of swaps | can be O(n²) | at most n - 1 | shifts can be O(n²) |
| Stable | yes | no | yes |
Stable means two equal values keep their original order.
TL;DR: Insertion sort sorts an array the way you arrange cards in your hand: the left part of the array is always sorted. On each pass, insertion sort takes the next number and saves it in current. The numbers on the left that are bigger than current shift one place to the right. Shifting stops at a number arr[j] that isn't bigger, and current goes into the gap right after it, at index j + 1. The loop starts at i = 1, the second number. Its worst case (reversed data) is O(n²), but on sorted or nearly sorted data it's only O(n). Its overhead (the extra work on top of comparing and shifting) is small too. That's why it's used for small data and inside built-in sorts like Timsort.
⚡ Take one, shift, insert
Write:
function insertionSort(arr) {
for (let i = 1; i < arr.length; i++) {
const current = arr[i]; // the number taken, like a card
let j = i - 1;
// shift the bigger ones right
while (j >= 0 && arr[j] > current) {
arr[j + 1] = arr[j];
j--;
}
arr[j + 1] = current; // insert
}
return arr;
}
Meaning: The left part of the array is always sorted, like the cards you already hold in a card game. Each pass saves the number at index i in current, like a new card. j moves back through the left part, and each number bigger than current shifts one place to the right. Then current goes into the gap at j + 1.
⚡ Save current first
Guess first: why not just write arr[j] > arr[i] in the while loop?
The first shift overwrites arr[i] with the number on its left. The number you took is lost, so the result is a mess. That's why it's saved first with const current = arr[i].
Meaning: Start at i = 1, because the number at index 0 has no number on its left. After the while loop, j points at a number that isn't bigger than current, so the gap is at j + 1, not at j.
⚡ Fast on nearly sorted data
Guess first: 1,000 numbers are sorted, except for two side-by-side numbers that are swapped. About how many comparisons does insertion sort need?
Only about 1,000. Almost every number needs just one comparison with the number on its left, then the while loop stops. Reversed data (in order from big to small) needs about 500,000.
Meaning: Reversed or shuffled data: O(n²). Sorted or nearly sorted data: O(n). Its overhead (the extra work on top of comparing and shifting) is small too. That's why insertion sort is often picked for small data, and is used inside Timsort, JavaScript's built-in sort in Chrome and Node.js.