代码
# coding=utf-8
# 事例
arr = [4, 11, 9, 12, 13, 7, 5, 6, 8, 20]
# 交换值
def swap(j):
arr[j] = arr[j] ^ arr[j+1]
arr[j+1] = arr[j] ^ arr[j + 1]
arr[j] = arr[j] ^ arr[j + 1]
#插入排序
def insertion():
for i in range(0,len(arr),1):
for j in range(i,0,-1):
if(arr[j] < arr[j-1]):
swap(j-1)
insertion()
运行结果:
i外循环 j内循环 | ||||||||||
---|---|---|---|---|---|---|---|---|---|---|
i=2,j=2 | 4 | 9 | 11 | 12 | 13 | 7 | 5 | 6 | 8 | 20 |
i=5,j=5 | 4 | 9 | 11 | 12 | 7 | 13 | 5 | 6 | 8 | 20 |
i=5,j=4 | 4 | 9 | 11 | 7 | 12 | 13 | 5 | 6 | 8 | 20 |
i=5,j=3 | 4 | 9 | 7 | 11 | 12 | 13 | 5 | 6 | 8 | 20 |
i=5,j=2 | 4 | 7 | 9 | 11 | 12 | 13 | 5 | 6 | 8 | 20 |
i=6,j=6 | 4 | 7 | 9 | 11 | 12 | 5 | 13 | 6 | 8 | 20 |
i=6,j=5 | 4 | 7 | 9 | 11 | 5 | 12 | 13 | 6 | 8 | 20 |
i=6,j=4 | 4 | 7 | 9 | 5 | 11 | 12 | 13 | 6 | 8 | 20 |
i=6,j=3 | 4 | 7 | 5 | 9 | 11 | 12 | 13 | 6 | 8 | 20 |
i=6,j=2 | 4 | 5 | 7 | 9 | 11 | 12 | 13 | 6 | 8 | 20 |
i=7,j=7 | 4 | 5 | 7 | 9 | 11 | 12 | 6 | 13 | 8 | 20 |
i=7,j=6 | 4 | 5 | 7 | 9 | 11 | 6 | 12 | 13 | 8 | 20 |
i=7,j=5 | 4 | 5 | 7 | 9 | 6 | 11 | 12 | 13 | 8 | 20 |
i=7,j=4 | 4 | 5 | 7 | 6 | 9 | 11 | 12 | 13 | 8 | 20 |
i=7,j=3 | 4 | 5 | 6 | 7 | 9 | 11 | 12 | 13 | 8 | 20 |
i=8,j=8 | 4 | 5 | 6 | 7 | 9 | 11 | 12 | 8 | 13 | 20 |
i=8,j=7 | 4 | 5 | 6 | 7 | 9 | 11 | 8 | 12 | 13 | 20 |
i=8,j=6 | 4 | 5 | 6 | 7 | 9 | 8 | 11 | 12 | 13 | 20 |
i=8,j=5 | 4 | 5 | 6 | 7 | 8 | 9 | 11 | 12 | 13 | 20 |