Skip to content

Module 18 · Algorithms and Problem Solving — topic 12 of 18

Insertion sort

Sorting the way people sort playing cards: inserting each element into its place in the sorted prefix, shifting elements, tracing inserts, excellent performance on nearly sorted data, stability, and sorting records by a key.

Beginner 10 min read·Lesson 272 of 306 in Python Programming

Learning objectives

  • Implement insertion sort
  • Trace insertions into the sorted prefix
  • Explain why it is fast on nearly sorted data

Definition

Insertion sort builds a sorted prefix one element at a time. Each new element is compared with elements of the sorted part from right to left; larger elements are shifted one place right until the correct position is found.

Introduction

When you pick up cards one by one and slide each into place among the cards already in your hand, you are doing insertion sort.

Why it matters

Insertion sort is the best of the simple sorts: fast on small or nearly sorted data, stable, and used inside Python's own Timsort for short runs.

Detailed explanation

Start with the first element as a sorted prefix of length 1.

Take the next element (the key). Move left through the sorted prefix, shifting each element greater than the key one place right.

Insert the key into the gap. The prefix is now one element longer.

Best case (already sorted): each key needs one comparison, so O(n). Worst case (reversed): O(n²) comparisons and shifts.

It is adaptive: the number of shifts equals the number of out-of-order pairs, so nearly sorted data is sorted very quickly.

It is stable because elements equal to the key are not shifted past it.

It sorts in place with O(1) extra memory and works well online — sorting items as they arrive.

A key function makes it sort records, such as students by marks, just like sorted(key=...).

Syntax

Python
def insertion_sort(items):
a = list(items)
for i in range(1, len(a)):
key = a[i]
j = i - 1
while j >= 0 and a[j] > key:
a[j + 1] = a[j]
j -= 1
a[j + 1] = key
return a
  • Grow a sorted prefix.
  • Shift larger elements right.
  • Fast on nearly sorted data.

Code examples

Insertion sort

Python
def insertion_sort(items):
a = list(items)
for i in range(1, len(a)):
key = a[i]
j = i - 1
while j >= 0 and a[j] > key:
a[j + 1] = a[j]
j -= 1
a[j + 1] = key
return a
print(insertion_sort([12, 11, 13, 5, 6]))
Output
[5, 6, 11, 12, 13]

Tracing each insertion

Python
a = [12, 11, 13, 5, 6]
for i in range(1, len(a)):
key = a[i]
j = i - 1
while j >= 0 and a[j] > key:
a[j + 1] = a[j]
j -= 1
a[j + 1] = key
print(f"insert {key}: {a}")
Output
insert 11: [11, 12, 13, 5, 6]
insert 13: [11, 12, 13, 5, 6]
insert 5: [5, 11, 12, 13, 6]
insert 6: [5, 6, 11, 12, 13]

More examples

Adaptive and stable

Python
def insertion_shifts(items):
a = list(items)
shifts = 0
for i in range(1, len(a)):
key = a[i]
j = i - 1
while j >= 0 and a[j] > key:
a[j + 1] = a[j]
j -= 1
shifts += 1
a[j + 1] = key
return shifts
print(insertion_shifts(range(10)), insertion_shifts([1, 2, 4, 3, 5, 6]), insertion_shifts(range(10, 0, -1)))
def insertion_sort_by(items, key):
a = list(items)
for i in range(1, len(a)):
current = a[i]
j = i - 1
while j >= 0 and key(a[j]) > key(current):
a[j + 1] = a[j]
j -= 1
a[j + 1] = current
return a
students = [("Asha", 85), ("Ravi", 78), ("Meera", 85), ("Kiran", 78)]
print([name for name, _ in insertion_sort_by(students, key=lambda s: s[1])])
Output
0 1 45
['Ravi', 'Kiran', 'Asha', 'Meera']

Step-by-step explanation

  • Sorted data needs no shifts; one swapped pair needs exactly one; reversed data needs 45.
  • The key function compares students by marks only.
  • Students with equal marks keep their original order (Ravi before Kiran, Asha before Meera) — the sort is stable.

Expected output

Running “Adaptive and stable” prints exactly:

TextOutput
0 1 45
['Ravi', 'Kiran', 'Asha', 'Meera']

Practical applications

  • Keeping a small leaderboard sorted as new scores arrive.
  • Sorting short runs inside Timsort.

Best practices

  • Prefer insertion sort among simple sorts.
  • Use it for small or nearly sorted data.
  • Use sorted() for general sorting.

Common mistakes

Using >= in the comparison

Avoid

while j >= 0 and a[j] >= key:

Prefer

while j >= 0 and a[j] > key:

>= shifts equal elements and breaks stability.

Important notes

  • bisect.insort combines binary search with insertion to keep a list sorted.

Key takeaways

  • Insertion sort inserts each element into a sorted prefix.
  • O(n) on sorted data, O(n²) in the worst case.
  • Stable, in place and adaptive.

Try it yourself

  1. 1
    Sort a list of words by length with insertion sort, keeping equal lengths in their original order.
  2. 2
    Count shifts for random, sorted and reversed lists of 100 numbers.

Finished reading? Mark it complete to update your dashboard.

Suggested practice

1 question test this exact topic. Answers and explanations are revealed after you submit.

  • AdvancedWhich of these sorts takes about O(n) time on an already sorted list?
Practise this topic