Skip to lesson content
navan✳THE BUILD LABPYTHON 3
0/101 complete
BUILD LAB / PYTHON/ Think in algorithms
EXPERIMENT 71 / 101

Make room for the next card.

Maintain a sorted prefix and recognise when existing order helps.

ADVANCED LAB
BY NAVAN SAMI◷ 10 MIN READPYTHON 3

01 The idea

Insertion sort takes the next item and shifts larger prefix items right until the new item fits. The prefix is sorted after every iteration. Its worst-case work is quadratic, but this implementation needs only linear comparisons when the data is already sorted. Small or nearly ordered inputs can therefore behave very differently from reverse-sorted inputs.

02 The experiment

Read it once. Predict what will happen. Then copy it into a .py file and run it in your local Python setup.

insertion_sort.py
def insertion_sort(values):
    result = list(values)
    for index in range(1, len(result)):
        item, position = result[index], index
        while position > 0 and result[position - 1] > item:
            result[position] = result[position - 1]
            position -= 1
        result[position] = item
    return result
print(insertion_sort([5, 2, 4, 1]))
↳ EXPECTED OUTPUT
[1, 2, 4, 5]

03 Under the hood

  1. 1

    Save the item before shifting the prefix; otherwise its original slot could be overwritten.

  2. 2

    The strict greater-than comparison leaves equal elements in their original relative order, making this form stable.

  3. 3

    The loop shifts references rather than repeatedly inserting into a new list. The copied input still consumes linear auxiliary space; a truly in-place variant would operate on the supplied list.

04 Your turn, builder

A SMALL MISSION

Test reverse order, duplicates, and already sorted input.

Reveal one possible solution +
one_possible_solution.py
def insertion_sort(values):
    result = list(values)
    for i in range(1, len(result)):
        item, j = result[i], i
        while j and result[j - 1] > item:
            result[j] = result[j - 1]; j -= 1
        result[j] = item
    return result
for values in [[3, 2, 1], [2, 2, 1], [1, 2, 3]]:
    assert insertion_sort(values) == sorted(values)
print("Insertion checks passed")

05 Check your signal

QUICK SIGNAL CHECK

Which input gives this insertion sort linear comparison work?

THAT’S ANOTHER IDEA IN YOUR TOOLKIT.

Experiment. Logged.

When you can explain the idea and make the example your own, mark it complete. Your log stays in this browser.

Keep exploring

Go deeper with the official Python guide ↗.

Built with curiosity. By Navan Sami. ↗Python 3 · Think. Try. Build.