Take each value and slide it backward over larger ones until it sits in its place in the sorted prefix.
Insertion sort works the way you sort a hand of playing cards: pick up the next card and slide it backward over the cards already in your hand until it lands in the right slot. The front of the list is a sorted prefix that grows by one each step. It's the go-to sort for small or nearly-ordered lists.
≥ the last prefix value, no shifting happens and the inner loop exits at once. On nearly-ordered data almost every insertion is instant, so the running time drops toward O(n) — the best behaviour of any simple sort.function insertionSort(arr) {
for (let i = 1; i < arr.length; i++) {
const key = arr[i];
let j = i - 1;
while (j >= 0 && arr[j] > key) { // slide larger values right
arr[j + 1] = arr[j];
j--;
}
arr[j + 1] = key; // drop the key into the gap
}
return arr;
}