Skip to content

Instantly share code, notes, and snippets.

@czheo
Last active February 2, 2017 05:33
Show Gist options
  • Star 0 You must be signed in to star a gist
  • Fork 0 You must be signed in to fork a gist
  • Save czheo/b872c8b7fc7b6ceb7a4f4952d5320749 to your computer and use it in GitHub Desktop.
Save czheo/b872c8b7fc7b6ceb7a4f4952d5320749 to your computer and use it in GitHub Desktop.
def insertion_sort(lst):
i = 1
# invarient:
# We keep the left part of the list sorted:
# [ ..sorted.. i ..unsorted.. ]
while i < len(lst):
# "target" is the item that we want to
# insert back to the left sorted part
# for example:
# [4, 5, 7, 9, 6, 3, 1, 2]
# ^
# |
# i (target)
target = lst[i]
# shift everything > target right by 1 offset
# for the same example
# [4, 5, x, 7, 9, 3, 1, 2]
# ^ ^ ^
# | | |
# j x i
j = i - 1
while j >= 0:
if lst[j] > target:
# shift everything > target right by 1 offset
lst[j+1] = lst[j]
j -= 1
else:
break
# save target back at the position x, which is j + 1
lst[j+1] = target
i += 1
# Now the list looks like:
# [4, 5, 6, 7, 9, 3, 1, 2]
# ^
# |
# next i
lst = [3,2,2,4,5,6,7,9,9,6,4,2,1]
insertion_sort(lst)
print(lst)
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment