Insertion Sort: Take the Next Card and Slide It Left Until It Fits
Emma's hand 7, 3, 9, 2, 5 sorted one card at a time in 6 shifts. Trace each card, see why a backwards hand costs the most, why 5,000 shuffled cards need over 6 million shifts, and why a sorted hand needs zero.
What you will learn
- Explain insertion sort the way you sort a hand of cards
- Trace each card sliding into the sorted part and count the shifts
- Say why shuffled input costs O(n²) and sorted input costs O(n)
- Read a small Python insertion sort with a while loop that shifts bigger cards right
Before you start
- Big-O: Reading Cost From Code
- Arrays and Dynamic Arrays
Emma is dealt five cards: 7, 3, 9, 2 and 5. She wants them smallest to largest, left to right: 2, 3, 5, 7, 9. While she sorts, count one thing: how many times a card has to slide over to make room. For this hand, that number turns out to be six.
Cards in your hand
Your left hand holds a sorted part. At the start, that's just the first card, the 7. One card on its own is always sorted. Pick up the next card, the 3. The 7 is bigger, so it slides one place right, and the 3 goes in front of it. Do the same for every card, one at a time, and the sorted part grows by one card each time.
The rule: take the next card, and slide it left past every bigger card until it fits. That's insertion sort.
Slide each card into place
- Pick up the 3. The card on its left is 7, which is bigger, so the 7 slides one slot right. You've reached the start of the hand, so drop the 3 into slot 0: 3, 7.
- Pick up the 9. Is 7 bigger than 9? No. The 9 stays where it is. No slide at all.
- Pick up the 2. 9, 7 and 3 are all bigger, so each one slides right. Drop the 2 into slot 0: 2, 3, 7, 9.
- Pick up the 5. 9 and 7 slide right, then 3 isn't bigger than 5, so stop. Drop the 5 into slot 2.
2, 3, 5, 7, 9, after 1 + 0 + 3 + 2 = 6 shifts.
The code
class CardSorter:
shifts = 0
show = True
@staticmethod
def sort(cards):
for i in range(1, len(cards)):
card = cards[i]
j = i - 1
while j >= 0 and cards[j] > card:
cards[j + 1] = cards[j] # slide it right
j -= 1
CardSorter.shifts += 1
cards[j + 1] = card # drop the card in
if CardSorter.show:
print(f"Card {card} to slot {j + 1}: {cards}")
The loop starts at card 1, not card 0, because card 0 alone is already sorted. j looks at the card on the left. The while keeps going while that card is bigger, and j >= 0 makes sure it stops at slot 0. Each pass slides a bigger card one slot right and counts a shift. Then the card drops into the gap.
from card_sorter import CardSorter
hand = [7, 3, 9, 2, 5]
CardSorter.sort(hand)
print("Sorted:", hand)
print("Shifts:", CardSorter.shifts)
Card 3 to slot 0: [3, 7, 9, 2, 5]
Card 9 to slot 2: [3, 7, 9, 2, 5]
Card 2 to slot 0: [2, 3, 7, 9, 5]
Card 5 to slot 2: [2, 3, 5, 7, 9]
Sorted: [2, 3, 5, 7, 9]
Shifts: 6
The order decides the work
The same five cards can cost very different amounts of work:
- Already in order: nothing slides. Each card is checked against the one on its left and stays put. Zero slides.
- One card out of place (a 7 that only has to pass a 9): one slide.
- Emma's mixed hand: six slides.
- Backwards (9, 7, 5, 3, 2): every card slides past everything before it, 1 + 2 + 3 + 4 = ten slides, the most it can ever be for five cards.
Draw each worst-case slide as a dot and you get a triangle: the second card slides at most once, the third at most twice, and so on. Double the hand to ten cards and the worst case isn't twenty slides; it's forty-five. A triangle grows fast when you stretch it.
A lot more cards
import random
from card_sorter import CardSorter
CardSorter.show = False
for n in (50, 500, 5_000):
random.seed(7)
cards = [random.randint(1, 999) for _ in range(n)]
CardSorter.shifts = 0
CardSorter.sort(cards) # shuffled
shuffled = CardSorter.shifts
CardSorter.shifts = 0
CardSorter.sort(cards) # now sorted
print(f"{n:7,d} cards: shuffled {shuffled:,},",
f"sorted {CardSorter.shifts}")
50 cards: shuffled 609, sorted 0
500 cards: shuffled 58,009, sorted 0
5,000 cards: shuffled 6,184,687, sorted 0
Ten times the cards, about a hundred times the shifts. Five thousand shuffled cards need over six million shifts. Sort the very same cards again, now in order, and it's zero. A mixed list of a hundred thousand would need about two and a half billion slides.
The cost
| Input | Cost | Why |
|---|---|---|
| Already sorted | O(n) | the while loop stops at once for every card |
| Almost sorted | close to O(n) | a few cards slide a short way |
| Shuffled | O(n²) | each card slides past about half the cards before it |
| Backwards | O(n²), the worst | each card slides past all of them |
A loop inside a loop gives about n times n. So insertion sort is great for a hand of cards or a list that is almost in order, and slow for a hundred thousand shuffled scores. Big lists need a faster way: merge sort or quick sort.
Where you meet insertion sort
- Sorting a hand of playing cards: it's what most people do without thinking.
- Inside bigger sorting methods, which cut a big list into small pieces and finish each piece this way, because on a few items it's quick.
- A leaderboard when a new score arrives: the list is already in order, so the new score just slides up until it fits.
Try it yourself
Give Emma the hand 9, 7, 5, 3, 2 and predict the number of shifts before you run it.
Related courses on Udemy
The Python Architect Masterclass: Full Stack to AI Engineer
Python, Django, FastAPI, React, Docker, AWS, LLMs, RAG, agents and MCP, from first steps to AI engineer.View on Udemy ↗: The Python Architect Masterclass: Full Stack to AI Engineer (paid course, opens in a new tab)Data Structures and Algorithms Concepts: No Coding Needed
How stacks, trees, hash tables, sorting and graphs really work, step by step, with pictures.View on Udemy ↗: Data Structures and Algorithms Concepts: No Coding Needed (paid course, opens in a new tab)Related posts
Big-O: Reading Cost From Code, With Handshakes and a Guest Book
Big-O asks one question: how do the steps grow when the list grows? Check a school trip sheet for duplicates two ways, handshakes and a guest book, count every step in Python, then grow the list to ten thousand ids and watch 10,000 steps turn into almost 50 million.
Recursion: Russian Dolls, the Base Case and the Call Stack
Recursion means doing the same job on a smaller piece of the problem, and stopping at a base case. Count Emma's Russian dolls with a Python function that calls itself, watch each call wait on the call stack so the answers come back in reverse, then take the base case out and meet RecursionError.
Linear vs Binary Search: Page by Page, or Open in the Middle
Is kite a real word? Page by page takes 11 checks; opening in the middle takes 4. Trace binary search step by step, see a million words answered in 20 checks, and watch it give the wrong answer on an unsorted list.
Merge Sort: Split the Pile, Then Merge Two Sorted Piles
Ms Kate's eight exam papers sorted in 24 steps: split in half until each pile is one paper, then merge sorted piles by taking the lower top. A million papers take about 20 million steps, and the price is extra room.
