← Algorithms · Lesson 2/11
Insertion sort
▶ Watch it as a video: one minute with LeIA
Like the cards in your hand
If you're dealt cards one at a time, you probably sort them like this: take the new one and insert it into its place among the ones you hold, sliding the bigger ones to the right. That's insertion sort.
In the program, i points at the number whose turn it is and saves it in x. Then j walks left: while a[j] is bigger than x, it shifts one place to the right (a[j + 1] = a[j]). When it finds one that's smaller or equal, or runs out of array, it drops x into the gap. Everything to the left of i is always sorted.
$ node leccion.js
Press RUN (or Ctrl+Enter).
What to look at
- There are no swaps: each bigger number shifts once, and
xis written at the end into the gap that's left. - Like bubble sort, it sorts in place and returns the same array.
The whole lesson on one page
Like the cards in your hand
If you're dealt cards one at a time, you probably sort them like this: take the new one and insert it into its place among the ones you hold, sliding the bigger ones to the right. That's insertion sort.
In the program, i points at the number whose turn it is and saves it in x. Then j walks left: while a[j] is bigger than x, it shifts one place to the right (a[j + 1] = a[j]). When it finds one that's smaller or equal, or runs out of array, it drops x into the gap. Everything to the left of i is always sorted.
function insercion(a) {
for (let i = 1; i < a.length; i++) {
const x = a[i];
let j = i - 1;
while (j >= 0 && a[j] > x) {
a[j + 1] = a[j];
j--;
}
a[j + 1] = x;
}
return a;
}
const lista = [5, 2, 8, 3, 7, 1, 6, 4];
console.log(insercion(lista));
- There are no swaps: each bigger number shifts once, and
xis written at the end into the gap that's left. - Like bubble sort, it sorts in place and returns the same array.
Step by step
The same function, with the inner loop split up so it can count: each turn compares once and, if a[j] isn't bigger, leaves with break. It prints the array after inserting each x and, at the end, how many comparisons and how many moves (a[j + 1] = a[j]) it made.
function insercion(a) {
let comparaciones = 0;
let movimientos = 0;
for (let i = 1; i < a.length; i++) {
const x = a[i];
let j = i - 1;
while (j >= 0) {
comparaciones++;
if (a[j] <= x) break;
a[j + 1] = a[j];
movimientos++;
j--;
}
a[j + 1] = x;
console.log("x =", x, "→", ...a);
}
console.log("comparisons:", comparaciones);
console.log("moves:", movimientos);
}
insercion([5, 2, 8, 3, 7, 1, 6, 4]);
- Watch the sorted part on the left grow: the 3 slips in between the 2 and the 5, the 1 travels all the way to the front.
- 20 comparisons and 15 moves. Those 15 are the same as bubble sort's swaps: each move fixes one pair that was out of order.
Nearly sorted, nearly free
The best thing about insertion sort: if the list is already sorted, each number is compared once with its neighbor and stays put. That's n - 1 comparisons: O(n). If it comes in reversed, every number travels all the way to the front: n(n - 1)/2, O(n²), same as bubble sort. Random input lands at about half of that.
That's why many real-world fast sorts use insertion sort for small or nearly sorted pieces: it's simple and wastes no work.
function comparaciones(a) {
let c = 0;
for (let i = 1; i < a.length; i++) {
const x = a[i];
let j = i - 1;
while (j >= 0) {
c++;
if (a[j] <= x) break;
a[j + 1] = a[j];
j--;
}
a[j + 1] = x;
}
return c;
}
// a thousand random numbers: always the same ones, because the seed is fixed
function alAzar(n) {
let s = 42;
return Array.from({ length: n }, () => (s = s * 16807 % 2147483647) % 1000);
}
const ordenada = Array.from({ length: 1000 }, (_, i) => i + 1);
const alReves = [...ordenada].reverse();
console.log("sorted: ", comparaciones(ordenada));
console.log("random: ", comparaciones(alAzar(1000)));
console.log("reversed:", comparaciones(alReves));
- Already sorted: 999 comparisons, one per number.
- Random: about 247,000, close to half the worst case.
- Reversed: 499,500, same as bubble sort.