Insertion Sort

Say you have a list of numbers and you want them in order. You could compare every pair and swap them around, but that feels messy, right? Insertion sort gives you a cleaner way. It picks up one item at a time and slides it into the right place among the items you have already sorted.

πŸƒ Think of Sorting Cards in Your Hand

Picture this. You are playing cards. The dealer gives you cards one by one and you keep them sorted in your hand.

You pick up the first card. Nothing to compare, so it just sits there. Then comes the second card. You look at it and slide it left or right so the two cards are in order. The third card arrives, and you push it into its correct spot among the two you already arranged.

That is exactly what insertion sort does. Insertion sort is a method that builds the sorted list one item at a time by taking the next item and placing it into its correct position among the already-sorted items.

The left part of your hand is always sorted. The right part is the pile you still need to deal with. Every new card moves from the unsorted pile into the sorted part.

🎯 What Problem Does It Solve?

Imagine a list that is already almost in order. Maybe one or two items are out of place. A heavy sorting method would still do a lot of work here, even though the list is almost done. That wastes time.

Insertion sort is great in this case. When the data is nearly sorted, it barely does any work. It walks through the list. It sees most items are already fine. It only nudges the few that are out of place.

So insertion sort is a good pick when:

  • The list is small.
  • The list is already nearly sorted.
  • You want something simple to write and easy to understand.

🧠 How It Works

Let us sort this small list: [5, 2, 4, 6, 1].

The idea is simple. We treat the first item as a sorted part of size one. Then we pick the next item, call it the key, and shift bigger items to the right to make room for it.

Here is the flow for one round:

Yes

No

Pick next item (key)

Compare key with item on its left

Left item bigger than key?

Shift left item one step right

Drop key into the gap

Move to next item

Let us watch the list change step by step. The part in bold is the sorted region.

Key we pick List after placing it
2 [2, 5, 4, 6, 1]
4 [2, 4, 5, 6, 1]
6 [2, 4, 5, 6, 1]
1 [1, 2, 4, 5, 6]

See how 6 did not move? It was already bigger than everything on its left, so it stayed put. That is the quick exit insertion sort takes when items are in order.

πŸ“ Steps to Do Insertion Sort

Before we write code, let us lay out the steps in plain words.

  1. Start from the second item. The first item is a sorted part by itself.
  2. Store the current item in a variable called key.
  3. Look at the items to the left of key, one by one, going leftward.
  4. As long as a left item is bigger than key, shift that item one step to the right.
  5. When you find an item that is not bigger (or you reach the start), drop key into the gap.
  6. Move to the next item and repeat until the list ends.

πŸ’» Insertion Sort in Code

Now let us turn those steps into code. The function takes a list, sorts it in place, and we print it before and after.

insertion_sort.py
# Sort the list in place using insertion sort
def insertion_sort(arr):
for i in range(1, len(arr)):
key = arr[i] # the item we want to place
j = i - 1
# shift bigger items one step to the right
while j >= 0 and arr[j] > key:
arr[j + 1] = arr[j]
j -= 1
arr[j + 1] = key # drop key into the gap
numbers = [5, 2, 4, 6, 1]
print("Before:", numbers)
insertion_sort(numbers)
print("After: ", numbers)

The output of the above code will be:

Output
Before: [5, 2, 4, 6, 1]
After: [1, 2, 4, 5, 6]

Note

The inner while loop is the heart of it. It keeps shifting bigger items to the right and stops the moment it meets an item that is not bigger than key. That stop is what makes insertion sort fast on nearly sorted data.

⏱️ How Fast Is It?

The speed depends on how messy the list is to begin with.

Think about the worst case first. The list is in reverse order. Now every new item has to travel all the way to the front, shifting everything. That gives us O(n^2) time, which means the work grows with the square of the list size.

Now think about the best case. The list is already sorted. Each new item is checked once against its left neighbor, sees it is fine, and stops. That is just O(n) time, one pass through the list.

Tip

Insertion sort sorts the list in place, so it uses only O(1) extra space. It is also stable, meaning two equal items keep their original order. That matters when you sort records by one field and want ties to stay as they were.

Here is the full picture in one table.

Case Time When it happens
Best O(n) List is already sorted
Average O(n^2) Items in random order
Worst O(n^2) List is in reverse order
Space O(1) Always, it sorts in place

⚠️ Common Mistakes

A few small slips trip up most beginners. Watch out for these.

  • Starting the outer loop at index 0 instead of 1. The first item is already a sorted part of size one, so you begin from the second item.
  • Forgetting to place key after the loop. The line arr[j + 1] = key is what actually drops the item in. Miss it and the value is lost.
  • Using arr[j] instead of key inside the while check. You stored the value in key for a reason. The slot arr[i] gets overwritten while you shift, so always compare against key.
  • Writing j-- in the wrong spot. The shift arr[j + 1] = arr[j] must come before you move j left, or you copy the wrong value.

🧩 What You’ve Learned

βœ… Insertion sort builds the sorted list one item at a time, like arranging cards in your hand.

βœ… It picks each item as a key, shifts bigger items to the right, then drops the key into the gap.

βœ… It runs in O(n) time on a sorted list and O(n^2) in the worst case, using only O(1) extra space.

βœ… It is stable and a great choice for small or nearly sorted data.

Check Your Knowledge

Test what you learned. Pick an answer for each question, then click Check.

  1. 1

    What does insertion sort do with each new item it picks?

    Why: Insertion sort takes each item and slides it into its correct position within the sorted part.

  2. 2

    Why is the best-case time of insertion sort O(n)?

    Why: When the list is already sorted, each key passes one comparison and the shifting loop stops immediately.

  3. 3

    How much extra space does insertion sort use?

    Why: Insertion sort rearranges items inside the same array, so it needs only a constant amount of extra space.

  4. 4

    Insertion sort is a good choice when the data is:

    Why: Its low overhead and fast best case make it ideal for small lists or lists that are nearly in order.

πŸš€ What’s Next?

Share & Connect