Think about the last time you played a card game. You picked up your cards one at a time and slid each one into the right spot in your hand. Low cards to the left, high cards to the right. You probably didn’t even think about it. Well, that’s insertion sort, and you’ve been using it since you were a kid.
It’s one of the friendliest sorting algorithms out there, and honestly one of the most useful to understand. In this guide, we’ll walk through how the insertion sort algorithm works, write it in Python, and see how it stacks up against bubble sort and selection sort. By the end, you’ll know exactly when it shines and when to leave it alone.
What Is Insertion Sort?
Insertion sort is a comparison-based sorting algorithm. It builds a sorted list one element at a time by taking the next value and inserting it into its correct position among the values that are already sorted.
Just like with selection sort, think of the list as having two parts:
- Sorted section: The values on the left that are already in order relative to each other.
- Unsorted section: The values on the right that still need to be placed.
At the start, the sorted section contains just the first element, because a single value is always “sorted” by itself. On each pass, insertion sort takes the first value from the unsorted section (we call it the key), compares it with the sorted values from right to left, shifts the bigger ones one step to the right, and drops the key into the gap.
The big difference from selection sort? Selection sort searches for the right value to place. Insertion sort already has the value in hand and searches for the right place.
How Does Insertion Sort Work? A Step-by-Step Example
Let’s sort the same list we used in our other sorting guides, in ascending order:
[29, 10, 14, 37, 13]
Watch Insertion Sort in Action
Follow the algorithm as it picks up each value and slides it into the right spot in the sorted section.
Array: [29, 10, 14, 37, 13]
Starting point
The first value, 29, is treated as the sorted section. Everything else is still waiting its turn.
Pass 1
- Pick up the next value,
10, as the key. - Compare it with
29. Since29is bigger, shift it one step to the right. - There's nothing left to compare, so place
10at the start.
The list is now [10, 29, 14, 37, 13]. The sorted section holds [10, 29].
Pass 2
- The key is
14. 29is bigger, so it shifts right.10is smaller, so we stop and place14right after it.
The list becomes [10, 14, 29, 37, 13].
Pass 3
The key is 37. We compare it with 29, and 29 is smaller, so 37 is already where it belongs. No shifting needed. The list stays [10, 14, 29, 37, 13].
Pass 4
- The key is
13. 37,29and14are all bigger, so each shifts one step right.10is smaller, so13goes into the gap right after it.
The result is [10, 13, 14, 29, 37]. Sorted! For a list of five values, insertion sort needs four passes. In general, it needs n - 1 passes.
Insertion Sort in Python
Once the card analogy clicks, the code is short and readable. The outer loop picks the next key, and the inner while loop shifts larger values to the right until it finds the key's home.
def insertion_sort(arr):
for i in range(1, len(arr)):
key = arr[i]
j = i - 1
# Shift larger values one step to the right
while j >= 0 and arr[j] > key:
arr[j + 1] = arr[j]
j -= 1
# Drop the key into its correct position
arr[j + 1] = key
return arr
numbers = [29, 10, 14, 37, 13]
print(insertion_sort(numbers))
# Output: [10, 13, 14, 29, 37]A few details are worth noticing:
- The outer loop starts at index
1, because the first element is already a sorted section of one. keystores the value we're inserting, so it isn't lost while we shift other values over it.- The
j >= 0check comes first on purpose. In Python,arr[-1]doesn't raise an error. It quietly reads the last element, which would cause a sneaky bug. - The comparison uses a strict
>, so equal values are never moved past each other. That's what keeps the sort stable.
The function sorts the list in place, so it changes the original list and returns that same list for convenience.
Insertion Sort Time and Space Complexity
Here's where insertion sort gets interesting. Unlike selection sort, the amount of work it does depends on how the data is arranged.
In the best case, the list is already sorted. Every key is compared once with the value to its left, found to be in the right place, and left alone. That's about n - 1 comparisons in total.
In the worst case, the list is in reverse order. Every key has to travel all the way to the front of the sorted section. The first key moves past 1 value, the second past 2, and so on:
1 + 2 + 3 + ... + (n - 1) = n(n - 1) / 2
That grows quadratically as the input gets larger.
| Case | Time complexity | Why? |
|---|---|---|
| Best | O(n) | The list is already sorted, so each key needs only one comparison and no shifts. |
| Average | O(n²) | On random data, each key moves about halfway through the sorted section. |
| Worst | O(n²) | The list is in reverse order, so every key shifts past every sorted value. |
Space complexity: O(1). Insertion sort works in place and only needs a few extra variables, such as i, j, and key.
Why Insertion Sort Is Great for Nearly Sorted Data
Algorithms that speed up when the input is close to sorted are called adaptive, and insertion sort is a classic example. If every element is only a few positions away from where it belongs, each key shifts just a handful of times. The running time then drops close to O(n) instead of O(n²).
That's a real advantage over selection sort, which does the same amount of scanning no matter what you hand it. It's also why insertion sort shows up inside bigger, faster algorithms. Hybrid sorts such as Timsort, the algorithm behind Python's built-in sorted() and list.sort(), use an insertion-style approach for small chunks of data, where its low overhead wins.
Insertion sort is also an online algorithm, which means it can sort values as they arrive. Think of a live leaderboard: each new score can be slotted into the existing sorted list without starting over.
Is Insertion Sort Stable?
Yes. Insertion sort is stable, as long as you use a strict comparison (>) when deciding whether to shift.
A stable sorting algorithm keeps equal items in their original relative order. This matters when you sort records by one field and want an earlier ordering preserved, for example sorting students by grade after they were already sorted by name.
Let's check with two equal values labelled 5a and 5b:
[5a, 5b, 2]The key 5b is compared with 5a. They're equal, so nothing shifts. Then the key 2 shifts both of them right, one after the other, and lands at the front:
[2, 5a, 5b]5a still comes before 5b, exactly like the original list. If you accidentally wrote >= instead of >, equal values would swap places and the stability would be gone.
Insertion Sort vs. Bubble Sort vs. Selection Sort
These three are usually taught together, and for good reason. All of them have O(n²) worst-case time, but they behave quite differently once you look closer:
| Feature | Insertion sort | Bubble sort* | Selection sort |
|---|---|---|---|
| Best-case time | O(n) | O(n) | O(n²) |
| Worst-case time | O(n²) | O(n²) | O(n²) |
| Stable? | Yes | Yes | No |
| Adaptive? | Yes | Yes* | No |
| Extra space | O(1) | O(1) | O(1) |
| Main strength | Fast on small or nearly sorted data | Simple to visualize | Few swaps |
*Bubble sort's best-case O(n) assumes the optimized version uses an early-exit check.
In practice, insertion sort usually beats the other two on small or partly sorted lists. It makes far fewer comparisons than bubble sort on typical data, and unlike selection sort it can finish early when the input is already in good shape. The one thing selection sort does better is minimizing writes, since it makes at most n - 1 swaps while insertion sort may shift many values.
Advantages and Disadvantages of Insertion Sort
Advantages
- Easy to understand and implement.
- Very fast on small lists and nearly sorted data.
- Stable, so equal elements keep their original order.
- Sorts in place using
O(1)extra space. - Works online, so it can handle values as they arrive.
Disadvantages
O(n²)average and worst-case time makes it a poor choice for large datasets.- It can perform many shifts when the data is in reverse order.
- Faster algorithms like merge sort and quicksort leave it behind as the input grows.
When Should You Use Insertion Sort?
For sorting big collections, you'll want your language's built-in sort instead. Those functions are heavily optimized and far more efficient at scale.
That said, insertion sort earns its place in several situations:
- Small lists. With only a handful of values, its low overhead often makes it faster than fancier algorithms.
- Nearly sorted data. If a list is almost in order, insertion sort finishes in close to linear time.
- Streaming or incoming data. It can insert each new value into an already sorted list.
- Inside hybrid algorithms. Many advanced sorts switch to an insertion-style method for small sections.
- Learning and interviews. It's a great way to practise loops, indexes and shifting, and interviewers love asking how it compares with other basic sorts.
Common Mistakes to Avoid
- Starting the outer loop at index 0. The first element is already a sorted section on its own, so begin at index
1. - Forgetting to save the key. If you don't store
arr[i]inkeyfirst, the first shift overwrites it and the value is lost. - Checking the index in the wrong order. Write
j >= 0 and arr[j] > key, not the other way round. Otherwise Python can readarr[-1]and give you wrong results without any error. - Inserting at the wrong index. After the loop ends,
jpoints to the value just before the gap, so the key belongs atj + 1. - Using
>=instead of>. It still sorts correctly, but it makes extra shifts and breaks stability.
Try It Yourself
Reading is a good start, but the idea really sticks once you've coded it. Here are a few challenges to try:
- Modify the Python function to sort the list in descending order.
- Add a counter to track how many comparisons and shifts the algorithm makes.
- Run it on an already sorted list, then on a reverse-sorted list, and compare the counts.
- Sort a list of tuples, such as
(name, grade), by grade and confirm that equal grades keep their original order.
Quick Recap
Insertion sort builds a sorted list one value at a time, sliding each new value into its correct spot, just like arranging a hand of cards. It's easy to follow, stable, works in place, and runs in close to O(n) time on nearly sorted data. The downside is its O(n²) average and worst-case time, which makes it a poor fit for large inputs.
Once you're comfortable with insertion sort, compare it side by side with bubble sort and selection sort, then level up to merge sort and quicksort. Seeing how those faster algorithms cut down the work is one of the best ways to build real intuition for algorithm efficiency.
Frequently Asked Questions
What is insertion sort in simple words?
It takes one value at a time and slides it into the correct position among the values that are already sorted, much like sorting playing cards in your hand.
What is the time complexity of insertion sort?
The best case is O(n) for an already sorted list. The average and worst cases are both O(n²).
What is the space complexity of insertion sort?
O(1). It sorts the list in place and needs only a few extra variables.
Is insertion sort stable?
Yes. As long as the shifting condition uses a strict comparison (>), equal elements keep their original relative order.
Is insertion sort better than bubble sort or selection sort?
For most small or nearly sorted lists, yes. All three share O(n²) worst-case time, but insertion sort adapts to the input, which gives it a best case of O(n). Selection sort can't do that, and bubble sort usually needs more comparisons and swaps in practice.
Is insertion sort used in real applications?
Rarely on its own for large data, but it's very common as a building block. Hybrid algorithms such as Timsort use insertion-style sorting on small chunks because it's fast and has little overhead.
When is insertion sort the best choice?
When the list is small, when it's already close to sorted, or when values arrive one at a time and need to be kept in order.
Found this helpful? Try implementing insertion sort in your favourite language, then run it against bubble sort and selection sort on the same lists. Counting comparisons and shifts side by side is the fastest way to see the differences for yourself.
