Skip to lesson content
navan✳THE BUILD LABDSA
0/66 complete
BUILD LAB / DSA/ The sorting workshop
EXPERIMENT 21 / 66

Make room for the next card.

Maintain a sorted prefix and recognise when existing order helps.

BY NAVAN SAMI◷ 8 MIN READCOREALGORITHM

01 Model 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.

THE THING THAT MUST STAY TRUE

The prefix before the current position is sorted.

02 State the strategy

Read the steps independently of syntax. Explain what each step preserves before translating it into code.

the_strategy.txt
TAKE the next value
SHIFT larger prefix values one place right
INSERT into the gap
REPEAT
ALGORITHM STUDIOLIVE IN YOUR BROWSER
38
0
12
1
57
2
24
3
8
4
46
5
31
6
COMPARISONS 0ARRAY WRITES 0STEP 1/40

Start with the original values. Predict the next comparison.

Change the experiment +
Current operation Ordered / visitedPredict. Step. Explain.

03 Make it concrete

The implementation uses Python 3.11+ with only the standard library. Run it locally, or download the independent DSA workbench.

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]
  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 Count the cost

TIME

O(n²) worst case; O(n) best case

SPACE

O(n) for the copied result

Bounds refer to the shown implementation and exclude printed output unless stated. n is input size; V and E are graph vertices and edges.

05 Your next move

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")

06 Check your reasoning

QUICK SIGNAL CHECK

Which input gives this insertion sort linear comparison work?

ANOTHER PATTERN IN YOUR TOOLKIT.

Understand it. Then own it.

Can you explain the invariant, trace an edge case, and defend the cost model? Log the experiment when the reasoning makes sense.

Built with curiosity. By Navan Sami. ↗Patterns over panic. One step at a time.