Explanation in the comments
def insertion_sort(array):
# For each number in the list (not starting
# with the first element because the first
# element has no prior (i.e., no array[j-1])
for i in range(1, len(array)):
# Set a temp variable j (totally not necessary
# but is helpful for the sake of a visual)
j = i
# While j is greater than 0 (position 0 is the
# very beginning of the array) AND the current
# element array[j] is less than the prior element
# array[j-1]
while j>0 and array[j] < array[j-1]:
# Set the current element equal to the prior
# element, and set the prior element equal to
# the current element (i.e., switch their positions)
array[j], array[j-1] = array[j-1], array[j]
# Decrement j (because we are moving each element
# towards the beginning of the list until it is
# in a sorted position)
j-=1
return array
array = [1, 5, 8, 3, 9, 2]
First for-loop iteration: [1,5,8,3,9,2]
(5
is already in a sorted position)
Second for-loop iteration: [1,5,8,3,9,2]
(8
is already in a sorted position)
Third: [1,3,5,8,9,2]
(move 3
back until it's sorted)
Fourth: [1,2,3,8,9]
(move 2
back until it's sorted)
Hope this slight illustration helps.