思路:
1.在第i轮通过列表的时候(1 <= i <= n-1),第i个项应该插入到列表的前i个项之中的正确位置
2.在第i轮之后,前i个项的顺序已经排好
以下是函数代码,我们设计的是一个升序排列的函数
def insertionSort(lyst):
i = 1
while i < len(lyst):
#将待插入的项赋值给itemToInsert
itemToInsert = lyst[i]
j = i - 1
while j >= 0:
#将itemToInsert依次与lyst[i-1] lyst[i-2]···进行比较,直到找到正确位置
if itemToInsert < lyst[j]:
#将第lyst[j]向后移一位
lyst[j + 1] = lyst[j]
j -= 1
else:
break
#将待插入项的值进行赋值
lyst[j + 1] = itemToInsert
i += 1
return lyst