Reading preferences
Concept

Insertion Sort

Keep part of a row in order, then make room and slide the next number into the right place.

sorting, insertion sort, sorted prefix, shifts, adaptive, stability

Insert into a sorted prefix

Imagine arranging playing cards in your hand. Keep the cards already picked up in order, then slide the next card into its proper place. Insertion Sort follows the same strategy with a list.

For example, your cards read [2, 5] and you pick up 4. Move 5 one place right to make a gap, then put 4 in the gap: [2, 4, 5]. You did not need to reorder everything. Insertion means putting something into a place between other items.

At the beginning, the first value alone is sorted. Each step takes the next value as a key, shifts larger predecessors right, and places the key in the gap.

Why learn it and where it is useful

What if most items are already ordered and just one new item arrives? Insertion Sort shows how to add that item without sorting the whole row from the beginning. Arranging cards in your hand is a familiar example of this idea.

The algorithm can work well for small or nearly ordered lists because there are few items to shift. More sophisticated sorting methods also use insertion on small portions. It is not generally fast for large backwards lists.

The invariant and the gap

The prefix is the left-hand part. Its numbers are in order for now, but a new, smaller number may still make them move. That is different from Selection Sort's prefix, whose numbers are already in their final places. The key is simply the next number we hold aside while making room.

Before processing position start, the prefix before that position is sorted. Saving the key lets us shift without losing it. Larger values move one position right until we reach a value no greater than the key, or the left boundary.

Inserting the key there leaves the enlarged prefix sorted. Repeating the step eventually makes the prefix cover the whole list.

A worked example

Key being insertedAfter insertionSorted prefix
Start[5, 2, 4, 1][5]
2[2, 5, 4, 1][2, 5]
4[2, 4, 5, 1][2, 4, 5]
1[1, 2, 4, 5][1, 2, 4, 5]

When inserting 1, first save it, then shift 5, 4, and 2 right. The temporary duplicate values during shifting are not the final result: the saved key restores the missing value when placed into the gap.

See the reasoning

Try Insertion Sort one decision at a time

Goal: smallest → largest. Taller bars mean bigger numbers. This is a teaching demonstration, not live Python execution.

  • Compare
  • Move
  • Final place
  1. 5
    Slot 1Not final
  2. 2
    Slot 2Not final
  3. 4
    Slot 3Not final
  4. 1
    Slot 4Not final
  5. 3
    Slot 5Not final

Held key: none. The ordered left-hand part can still move when a new number is inserted.

Start

Our goal is smallest to largest. Each bar is one number; a taller bar means a larger number.

Python illustration

def insertion_sort(values):
    for start in range(1, len(values)):
        key = values[start]
        index = start - 1
        while index >= 0 and values[index] > key:
            values[index + 1] = values[index]
            index -= 1
        values[index + 1] = key
    return values

print(insertion_sort([5, 2, 4, 1]))

Prepared output — not live execution:

[1, 2, 4, 5]

The boundary check comes first because Python permits negative list indices. The and short-circuits when index becomes negative, avoiding an unintended comparison with the end of the list. Empty and one-element inputs need no work.

Complexity and existing order

Count how many cards must move to make room. If the row is already ordered, the next card fits after its left neighbour and no shift is needed. If it is backwards, each new card must pass all the cards before it.

In the notation below, n is the number of cards, O(n) describes roughly linear work, O(n²) describes roughly square growth, and O(1) extra space means only a small fixed amount of extra storage is needed.

An already sorted list makes one failed greater-than test per insertion and no shifts: best-case time is O(n). A reverse-sorted list shifts every preceding value, for 1 + 2 + ... + (n - 1) shifts: worst-case time is O(n²). Average time under a random-order model is also O(n²), with O(1) extra space.

An inversion is a pair whose earlier value is larger than its later value. Each shift removes one such out-of-order pair. With constant-time comparisons and moves, this implementation's work is O(n + I), where I is the initial number of inversions. That explains why a small nearly sorted collection can be a good fit.

Stability and limitations

Only strictly larger values move past the key. Equal keys keep their original relative order, so this implementation is stable and in place.

Insertion Sort is useful for small inputs and appears inside more sophisticated sorting implementations. It is not an efficient general solution for large, randomly ordered lists. A cheaper position search alone would not eliminate the cost of shifting many elements.

Return to the sorting overview to compare these three strategies.

Reflect on the concept

Four fixed questions to reinforce the reasoning. Answers are not saved or scored.

1. Which values are shifted when inserting the next key?
2. Why save the next value in a key variable?
3. Why can Insertion Sort be efficient on nearly sorted input?
4. Why check index >= 0 before accessing values[index]?

References and further reading