Insertion Sort in Python
Learn the Insertion Sort algorithm in Python! Beginner-friendly, step-by-step visual explanation with clean, runnable Python code.
Try it yourself
Run this code directly in your browser. Click "Open in full editor" to experiment further.
Click Run to see output
Or press Ctrl + Enter
How it works
Insertion Sort is the way most people naturally sort a hand of playing cards. ๐
The Real-World Analogy
Imagine you're being dealt cards one at a time. You hold the cards you already have in your left hand (the sorted pile). Each new card you pick up, you slide left through your hand until it lands in the right spot. That's it โ that's the whole algorithm.
How It Works
1. Treat the first element as a sorted list of size 1.
2. Take the next element (the "current card").
3. Walk leftward through the sorted part, sliding any larger element one step to the right.
4. Drop the current card into the gap you just opened.
5. Repeat until you've placed every card.
At every step, the left side of the array stays perfectly sorted โ it just keeps growing by one.
Why Use It?
Time Complexity
while loop never runs.Insertion Sort vs Bubble Sort
Both are O(n^2), but insertion sort usually wins in practice:
Learn this one well โ it's the sorting algorithm you'll use the most in your own head. ๐ง
Related examples
Bubble Sort in Python
Learn the Bubble Sort algorithm in Python! Step-by-step visual explanation with beginner-friendly, optimized Python code.
Quick Sort in Python
Learn Quick Sort in Python! A beginner-friendly guide to the famous Divide and Conquer algorithm. See how pivots and partitioning make sorting blazing fast.
Merge Sort in Python
Learn Merge Sort in Python! A fun, beginner-friendly guide to the Divide and Conquer sorting strategy with guaranteed fast performance.