Insertion sort
Beginner · 7 min · code in PHP, JavaScript, Java and Go
Where you will meet this in real life
Insertion sort takes items one at a time and slides each into its correct place among those already sorted, just like arranging playing cards in your hand. It is very fast when the data is already nearly sorted and works well on a stream of arriving items.
Practical use cases
- Web app: Live leaderboard that keeps itself tidy. A quiz app shows a ranked list, and every few seconds a new score arrives. Instead of sorting the entire board again, the code slides the new score up from the bottom until it reaches its place. Updates feel instant even with a few hundred players on screen.
- Web app: Newest comment placed in order. A comments section is ordered by time, and a late-arriving comment from a slow connection must be slotted into the right place. The existing list is already sorted, so only the newcomer needs to move. Readers see their comment appear at the right spot straight away.
- System: Finishing step of faster sorts. Real-world sort routines in language libraries often use insertion sort for tiny chunks, because on 10 or 20 items it beats fancier methods. It is a hidden helper inside the sort you call every day, and a reminder that simple methods still matter.
The story: Grandpa's Hand of Cards
Every Diwali the family sat on the floor for a long game of cards. Grandpa Bhaskar always had his cards perfectly arranged, low to high, and he never seemed to spend time on it. Mira finally asked how.
"I never sort the whole hand", he laughed. "When a new card is dealt, I look at the cards I already hold. They are already in order. I just find the right gap, slide the bigger ones a little to the right, and tuck the new card in."
Kabir tried it with a handful of cards. First card: already sorted, because it is alone. Second card: compare with the first, slide if needed. Third card: walk left past the bigger ones until the gap is found. Each new card is only compared with the cards that are already in order.
This is insertion sort. It shines when the cards are already nearly in order, because then each card finds its gap almost immediately.
How to spot this problem, and where you need it
Your list is already mostly in order, or items arrive one at a time and must be placed in the right spot, and re-sorting everything each time is wasteful.
Signs you need it
- You keep a sorted list and add one new item at a time, then call sort again on the whole list.
- The data is almost sorted, such as yesterday data with a few late changes, so very little needs to move.
- The list is tiny, such as 10 to 30 elements, where simple code beats clever code.
Where to use it in a project
- Live rankings, price ladders and activity feeds where single updates arrive continuously.
- Final cleanup of nearly sorted data, such as an already ordered export with a few edits.
The solution
Treat the left side of the list as sorted. Take the next item, and compare it with the items on its left, moving each larger one a step right. Drop the item into the gap that opens. Continue with the next item. If the data is nearly sorted, each item barely moves, so the whole thing finishes in about one pass.
Payoff: Before: re-sorting 500 scores on every update. After: each new score moves a few places, and the board refreshes instantly.
Explain it like I am 8
You are picking up playing cards one at a time. Each new card, you slide it to the left through your hand until it sits right between a smaller card and a bigger card. Your hand is always neatly ordered.
How it works, step by step
- Treat the first item as a tiny sorted hand of one card.
- Take the next item and call it the
key. - Walk left through the sorted hand. Every item bigger than the key slides one step right.
- Stop when you meet a smaller (or equal) item, or the start of the list, and drop the key into the gap.
- Repeat for every remaining item. Using "bigger than" (not "bigger or equal") keeps equal items in their original order.
The code in four languages
PHP
<?php
// Insertion sort: grow a sorted hand on the left, one card at a time.
function insertionSort(array $a): array {
for ($i = 1; $i < count($a); $i++) {
$key = $a[$i]; // the card we just picked up
$j = $i - 1;
while ($j >= 0 && $a[$j] > $key) {
$a[$j + 1] = $a[$j]; // slide bigger cards one step right
$j--;
}
$a[$j + 1] = $key; // drop the card into the gap
}
return $a;
}
echo implode(', ', insertionSort([6, 3, 5, 1, 4])); // 1, 3, 4, 5, 6JavaScript
// Insertion sort: grow a sorted hand on the left, one card at a time.
function insertionSort(input) {
const a = [...input];
for (let i = 1; i < a.length; i++) {
const key = a[i]; // the card we just picked up
let j = i - 1;
while (j >= 0 && a[j] > key) {
a[j + 1] = a[j]; // slide bigger cards one step right
j--;
}
a[j + 1] = key; // drop the card into the gap
}
return a;
}
console.log(insertionSort([6, 3, 5, 1, 4]).join(', ')); // 1, 3, 4, 5, 6Java
import java.util.*;
public class Main {
// Insertion sort: grow a sorted hand on the left, one card at a time.
static int[] insertionSort(int[] input) {
int[] a = input.clone();
for (int i = 1; i < a.length; i++) {
int key = a[i]; // the card we just picked up
int j = i - 1;
while (j >= 0 && a[j] > key) {
a[j + 1] = a[j]; // slide bigger cards one step right
j--;
}
a[j + 1] = key; // drop the card into the gap
}
return a;
}
public static void main(String[] args) {
System.out.println(Arrays.toString(insertionSort(new int[]{6, 3, 5, 1, 4}))); // [1, 3, 4, 5, 6]
}
}Go
package main
import (
"fmt"
"slices"
)
// insertionSort: grow a sorted hand on the left, one card at a time.
func insertionSort(input []int) []int {
a := slices.Clone(input)
for i := 1; i < len(a); i++ {
key := a[i] // the card we just picked up
j := i - 1
for j >= 0 && a[j] > key {
a[j+1] = a[j] // slide bigger cards one step right
j--
}
a[j+1] = key // drop the card into the gap
}
return a
}
func main() {
fmt.Println(insertionSort([]int{6, 3, 5, 1, 4})) // [1 3 4 5 6]
}Time: O(n²) worst, O(n) best · Extra space: O(1). On a reversed list every card slides all the way back (slow); on a sorted list no card slides at all (fast).
Watch out for
- Overwriting
a[j + 1]without saving the key first, so the card is lost. - Using
>=in the while condition. It still sorts, but it needlessly moves equal items and makes the sort unstable. - Forgetting
j >= 0in the loop, which reads before the start of the list.
Quick check
- What does insertion sort keep true after each step?
- The left part is sorted
- The smallest item is in the last spot
- The list is half sorted everywhere
- On which input is insertion sort at its fastest?
- A reversed list
- A random list
- An already sorted list
- Why does the key get saved in a variable?
- To print it later
- Because sliding cards right overwrites its original spot
- Because arrays are read-only