算法核心:排序数组,将一个数按大小插入到一个有序的数组中即可。
代码:
def insert_sort_1(List):
for i in range(1,len(List)):
#在实践中写的另一种,依次与前方数组的数进行对比,发现插入的值大就交换位置
j=i-1
while(j>=0 and List[i]<List[j]):
List[j],List[i]=List[i],List[j]
j=j-1
i=i-1
print(i)
print(List)
def insert_sort_2(List):
#算法导论中的代码,将要插入的值,依次与前方的有序数组中的数进行对比
#如果比要插入的值大,则有序数组对应部分向后移,最后将值插入
for i in range(1,len(List)):
key=List[i]
j=i-1
while(j>=0 and key<List[j]):
List[j+1]=List[j]
j=j-1
List[j+1]=key
print(i)
print(List)
a=[3,1,5,4,12,5,2,5]
b=[3,1,5,4,12,5,2,5]
insert_sort_1(a)
insert_sort_2(b)
print(a)
print(b)
结果:
[1, 2, 3, 4, 5, 5, 5, 12]
[1, 2, 3, 4, 5, 5, 5, 12]