2022-12-05 17:53:38 +00:00
|
|
|
# This function sorts a list (like list.sort)
|
|
|
|
# using the insertion sort algorithm.
|
|
|
|
# Modify it to accept a key= keyword argument that works like in list.sort.
|
|
|
|
|
2022-12-21 10:37:42 +00:00
|
|
|
def insertionSort(lst, key=None):
|
2022-12-05 17:53:38 +00:00
|
|
|
# Traverse elements starting at position 1
|
|
|
|
for i in range(1, len(lst)):
|
|
|
|
# We know that lst[:i] is sorted
|
2023-05-16 20:00:37 +00:00
|
|
|
x = lst[i] # x is the element to insert next
|
2022-12-05 17:53:38 +00:00
|
|
|
# Elements in lst[:i] that are > x must move one position ahead
|
|
|
|
j = i - 1
|
2022-12-21 10:37:42 +00:00
|
|
|
while j >= 0 and (key(lst[j]) > key(x) if key else lst[j] > x):
|
2022-12-05 17:53:38 +00:00
|
|
|
lst[j + 1] = lst[j]
|
|
|
|
j -= 1
|
|
|
|
# Then put x in the last emptied slot
|
|
|
|
lst[j + 1] = x
|
|
|
|
# Now we know that lst[:i+1] is sorted
|
|
|
|
return
|
|
|
|
|
|
|
|
|
|
|
|
def main():
|
|
|
|
# Original list
|
|
|
|
lst0 = ["paulo", "augusto", "maria", "paula", "bernardo", "tito"]
|
|
|
|
print("lst0", lst0)
|
|
|
|
|
|
|
|
# sort in lexicographic order:
|
|
|
|
lst = lst0.copy()
|
|
|
|
insertionSort(lst)
|
|
|
|
print("lst1", lst)
|
|
|
|
assert lst == sorted(lst0)
|
|
|
|
|
|
|
|
# sort by length (requires key= argument):
|
|
|
|
lst = lst0.copy()
|
|
|
|
insertionSort(lst, key=len)
|
|
|
|
print("lst2", lst)
|
|
|
|
assert lst == sorted(lst0, key=len)
|
|
|
|
|
|
|
|
# sort by length, than lexicographic order:
|
2023-05-16 20:00:37 +00:00
|
|
|
myorder = lambda s: (len(s), s)
|
2022-12-05 17:53:38 +00:00
|
|
|
lst = lst0.copy()
|
|
|
|
insertionSort(lst, key=myorder)
|
|
|
|
print("lst3", lst)
|
|
|
|
assert lst == sorted(lst0, key=myorder)
|
|
|
|
|
|
|
|
print("All tests OK!")
|
|
|
|
|
2022-12-21 10:37:42 +00:00
|
|
|
|
2022-12-05 17:53:38 +00:00
|
|
|
if __name__ == "__main__":
|
|
|
|
main()
|