Single logo
  • Courses
  • Blog
  • About
Join on SkoolJoin on Skool

In this topic

Data Structures and Algorithms
  • What a Data Structure Is, and How Memory Works
  • Arrays and Dynamic Arrays: Full? Get a Box Twice the Size
  • Linked Lists: A Chain of Clues, Built in Python
  • Stacks: Last In, First Out, With the Undo Button
  • Queues: First In, First Out, With a Ring of Cells
  • Hash Tables: The Name Tells You Where to Look
  • Binary Search Trees: Smaller Left, Bigger Right, Half Gone at Every Look
  • Tree Traversals: In-Order, Pre-Order and Post-Order as a Tour of the House
  • Heaps and Priority Queues: Most Urgent First, Without Searching the Room
  • Graphs and Breadth-First Search (BFS): Fewest Hops, Level by Level
  • Big-O: Reading Cost From Code, With Handshakes and a Guest Book
  • Recursion: Russian Dolls, the Base Case and the Call Stack
  • Linear vs Binary Search: Page by Page, or Open in the Middle
  • Insertion Sort: Take the Next Card and Slide It Left Until It Fits
  • Merge Sort: Split the Pile, Then Merge Two Sorted Piles
  • Quick Sort: Line Up Around One Friend, Then Repeat on Each Side
  • Depth-First Search (DFS): Go Deep, Back Up, Mark Where You've Been
  • The Two Pointers Technique: Find a Pair in One Pass Instead of Every Pair
  • The Sliding Window Technique: One In, One Out
  • Greedy Algorithms: The Best-Looking Choice, Right Now
  • Dynamic Programming: Work It Out Once, Write It Down, Read It Back
  1. Blog
  2. /
  3. Data Structures and Algorithms
  4. /
  5. Algorithms

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.

Chaand Sheikh

·27 November 2026·Updated 28 November 2026Algorithms

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.

Insertion sort on 7 3 9 2 5: each row shows the sorted part growing by one card; 3 goes to slot 0 with 1 shift, 9 stays with 0, 2 goes to slot 0 with 3 shifts, 5 goes to slot 2 with 2 shifts, total 6 startcard 3card 9card 2card 5 1 shift0 shifts3 shifts2 shifts 7 3 9 2 5 3 7 9 2 5 3 7 9 2 5 2 3 7 9 5 2 3 5 7 9
Green is the sorted part; red is the card just dropped in. Six shifts in all.

Slide each card into place

  1. 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.
  2. Pick up the 9. Is 7 bigger than 9? No. The 9 stays where it is. No slide at all.
  3. 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.
  4. 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

InputCostWhy
Already sortedO(n)the while loop stops at once for every card
Almost sortedclose to O(n)a few cards slide a short way
ShuffledO(n²)each card slides past about half the cards before it
BackwardsO(n²), the worsteach 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.

Tried the exercise? Share your answer or ask a question.

The StudyEasy AI Community is free to join, with the lesson files, notebooks and code.

Join free on Skool

Keep going in Data Structures and Algorithms · 14 of 21

Previous
Linear vs Binary Search: Page by Page, or Open in the Middle
Next post
Merge Sort: Split the Pile, Then Merge Two Sorted Piles

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.

On this page

  • Cards in your hand
  • Slide each card into place
  • The code
  • The order decides the work
  • A lot more cards
  • The cost
  • Where you meet insertion sort
  • Try it yourself
Community · Free to join
Single logo

StudyEasy AI Community

Hosted onSkool

Learn AI engineering, share what you build, and connect with other learners.

  • Free resources: lesson files, notebooks and code

  • Ask questions and join engineering discussions

  • Meet real people learning and building with AI

Join free on Skool

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)

Single logo

Empowering Education, One Course at a Time

About
About usContact us
Legal
Terms of UsePrivacy Policy

© 2026 StudyEasy Organization. All rights reserved.