Last active
February 2, 2017 05:33
-
-
Save czheo/b872c8b7fc7b6ceb7a4f4952d5320749 to your computer and use it in GitHub Desktop.
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
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