Insertion Sort
Sorting: lesson 4 of 8
Build a sorted run, slide each newcomer into place.
Lesson 4 of 8 · 5 min
Insertion Sort
Step 1 of 18
sorted1 of 6shifts0
k
4
1
5
2
6
3
Treat the first value as a sorted region of one, then absorb the rest one at a time.
The Idea
Treat the left side as already sorted and pick up the next element. Shift the bigger values one slot right until a gap opens, then drop it in. Generally O(n²), but close to O(n) on nearly sorted data.
Real-World Example
A barista clips order tickets onto a rail kept in pickup-time order. A new ticket slides past the later ones until it finds its slot, usually only a step or two, because it is typically the latest anyway.
The Code
def insertion_sort(nums):
for i in range(1, len(nums)):
key = nums[i]
j = i - 1
# slide bigger values one slot to the right
while j >= 0 and nums[j] > key:
nums[j + 1] = nums[j]
j -= 1
nums[j + 1] = key # drop key into the gap
return nums
# insertion_sort([7, 3, 9, 3]) -> [3, 3, 7, 9]
Your turn
What does this print?
nums = [2, 5, 9, 0]
key, j = 4, 2
while j >= 0 and nums[j] > key:
nums[j + 1] = nums[j]
j -= 1
nums[j + 1] = key
print(nums)Mini quiz
1 / 3