0.介绍
动图表示
1.代码实现
def insertion_sort(arr):
for i in range(len(arr)):
preIndex = i - 1
current = arr[i]
while preIndex >= 0 and arr[preIndex] > current:
arr[preIndex + 1] = arr[preIndex]
preIndex -= 1
arr[preIndex + 1] = current
return arr
完整代码
import random
def insertion_sort(arr):
for i in range(len(arr)):
preIndex = i - 1
current = arr[i]
while preIndex >= 0 and arr[preIndex] > current:
arr[preIndex + 1] = arr[preIndex]
preIndex -= 1
arr[preIndex + 1] = current
return arr
def main():
arr = []
for _ in range(10):
arr.append(random.randint(1, 100))
print("-" * 15 + "before sorted" + "-" * 15)
print(arr)
list = insertion_sort(arr)
print("-" * 15 + "after sorted " + "-" * 15)
print(list)
if __name__ == "__main__":
main()
运行结果