def insertion_sort(array = []):
'''
循环遍历列表中每个元素
'''
for i in range(0, len(array), 1):
cur_index = i
'''
从当前元素位开始,若当前位元素大于前一位元素,则两者交换位置
一直向前重复比较
'''
while array[cur_index-1] > array[cur_index] and cur_index-1 >= 0:
array[cur_index], array[cur_index-1] = array[cur_index-1], array[cur_index]
cur_index -= 1
return array
# 输入列表
num = [1, 5, 4, 2, 23, 15, 2, 45, 56, 7, 8, 9]
num = insertion_sort(num)
print(num)
'''
[1, 2, 2, 4, 5, 7, 8, 9, 15, 23, 45, 56]
'''
插入排序法(InsertionSorting)python
于 2022-11-09 20:21:16 首次发布