Insertion_Sort插入排序

 1 A=[5,2,4,6,1,3]
 2 def Insertion_Sort(A):
 3     #把第j个元素插入到【0,j-1】中,从第0个元素开始
 4     for j in range(1,len(A)):
 5         key=A[j]
 6         i=j-1
 7         #i从(j-1)到 0,i向前进1,直到要插入元素比前面的元素大
 8         # 从第j-1个元素和要插入的元素比较到,从第0个元素和要插入的元素比较
 9         while i>=0 and A[i]>key:
10             A[i+1]=A[i]
11             i=i-1
12             A[i+1]=key
13     return A
14 
15 print(Insertion_Sort(A))
16 ------------------------------------
17 [1, 2, 3, 4, 5, 6]
插入排序

猜你喜欢

转载自www.cnblogs.com/yu-liang/p/9163398.html
今日推荐