This Insertion Sort lesson is for a beginner. Read the short notes, run each example, then change one name or number and run it again.
Insertion sort takes the next item and slides it left until it sits in order among the items already sorted.
It is quick when the list is short or already nearly sorted.
Example 1: Start here
The left side of i is always sorted.
def insertion(items): # define the function; it runs when you call it
items = items[:] # a separate copy
for i in range(1, len(items)): # repeat once per number; range stops before the last
value = items[i] # the value at this position
j = i - 1 # the result of this math
while j >= 0 and items[j] > value: # keep repeating while this stays true
items[j + 1] = items[j] # change this one field
j -= 1 # update the stored value
items[j + 1] = value # change this one field
return items # send this value back to the caller
print(insertion([4, 1, 3]))
Example 2: Walk the values
Insertion Sort starts by visiting one value at a time. Read the printed lines from top to bottom.
values = [27, 3, 11, 7] # a list; the values stay in this order
for value in values: # repeat the indented lines once per value
print(value)
Example 3: Keep the largest
Many data-structure lessons reduce a list to one answer. This one remembers the largest number seen so far.
values = [27, 3, 11, 7] # a list; the values stay in this order
best = values[0] # the first value
for value in values: # repeat the indented lines once per value
if value > best: # run the indented lines only when this is true
best = value # another name for the same value
print(best)
Example 4: Search for a target
A search asks one yes-or-no question: is the target in the collection? Insertion Sort builds on that question.
values = [3, 27, 11] # a list; the values stay in this order
target = 27 # a whole number
print(target in values) # in is True when the value is found
