插入排序执行过程
#encoding = utf-8
a=[1,9,0,8,3,7,5,6]
#插入排序
#核心是每次插入一个数的时候,都把这个数前面的数当做一个排好序的数列
#插入数据的过程是,把这个数跟前面的数据依次的比较,如果比前面的数小,那就把它放到这个数前面,插入过程结束
#内层循环执行插入的动作,外层循环每次给内层循环一个序列,从最左边开始,每次在序列后加一个数,需要处理len(a)-1次
print u"插入排序"
print "a before change:",a
for i in range(0,len(a)-1-1):
print "i:",i
for j in range(i,-1,-1):
print "j:",j
if a[j+1] < a[j]:
print "a[j+1] < a[j]"
a[j+1],a[j] = a[j],a[j+1]
print a
print "a after change:",a
结果:
D:\>python test.py
插入排序
a before change: [1, 9, 0, 8, 3, 7, 5, 6]
i: 0
j: 0
[1, 9, 0, 8, 3, 7, 5, 6]
i: 1
j: 1
a[j+1] < a[j]
[1, 0, 9, 8, 3, 7, 5, 6]
j: 0
a[j+1] < a[j]
[0, 1, 9, 8, 3, 7, 5, 6]
i: 2
j: 2
a[j+1] < a[j]
[0, 1, 8, 9, 3, 7, 5, 6]
j: 1
[0, 1, 8, 9, 3, 7, 5, 6]
j: 0
[0, 1, 8, 9, 3, 7, 5, 6]
i: 3
j: 3
a[j+1] < a[j]
[0, 1, 8, 3, 9, 7, 5, 6]
j: 2
a[j+1] < a[j]
[0, 1, 3, 8, 9, 7, 5, 6]
j: 1
[0, 1, 3, 8, 9, 7, 5, 6]
j: 0
[0, 1, 3, 8, 9, 7, 5, 6]
i: 4
j: 4
a[j+1] < a[j]
[0, 1, 3, 8, 7, 9, 5, 6]
j: 3
a[j+1] < a[j]
[0, 1, 3, 7, 8, 9, 5, 6]
j: 2
[0, 1, 3, 7, 8, 9, 5, 6]
j: 1
[0, 1, 3, 7, 8, 9, 5, 6]
j: 0
[0, 1, 3, 7, 8, 9, 5, 6]
i: 5
j: 5
a[j+1] < a[j]
[0, 1, 3, 7, 8, 5, 9, 6]
j: 4
a[j+1] < a[j]
[0, 1, 3, 7, 5, 8, 9, 6]
j: 3
a[j+1] < a[j]
[0, 1, 3, 5, 7, 8, 9, 6]
j: 2
[0, 1, 3, 5, 7, 8, 9, 6]
j: 1
[0, 1, 3, 5, 7, 8, 9, 6]
j: 0
[0, 1, 3, 5, 7, 8, 9, 6]
a after change: [0, 1, 3, 5, 7, 8, 9, 6]