Make room for the next card.
Maintain a sorted prefix and recognise when existing order helps.
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 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.
TAKE the next value
SHIFT larger prefix values one place right
INSERT into the gap
REPEATStart with the original values. Predict the next comparison.
Change the experiment +
03 Make it concrete
The implementation uses Python 3.11+ with only the standard library. Run it locally, or download the independent DSA workbench.
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]))[1, 2, 4, 5]
- 1
Save the item before shifting the prefix; otherwise its original slot could be overwritten.
- 2
The strict greater-than comparison leaves equal elements in their original relative order, making this form stable.
- 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
O(n²) worst case; O(n) best case
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
Test reverse order, duplicates, and already sorted input.
Reveal one possible solution +
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
Which input gives this insertion sort linear comparison work?
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.