B2.4.3 · Sorting
Insertion sort · extension
Python · step by step
Insertion sort · extension
Watch the list change while following the actual Python execution.
Python implementation
1def insertion_sort(items):2 for i in range(1, len(items)):3 key = items[i]4 j = i - 15 while j >= 0 and items[j] > key:6 items[j + 1] = items[j]7 j = j - 18 items[j + 1] = key9 return items Optional extension, not one of the two named B2.4.3 sorts. Keep key aside while shifting larger values; the prefix grows in sorted order. O(n) best-case and O(n²) worst-case time; O(1) auxiliary space.
Keep exploring
Return to the sorting lesson →
All B2.4 animations →