插入排序主要的思想是插入第i个元素到前i-1个已经排好序的序列中,将第i个元素与第i-1个元素相比较,如果大于等于,则将第i个元素放在后面。如果第i个元素小于第i-1的元素,则互换二者的位置,再比较待插入元素与第i-2个元素的大小,直到将待插入元素放到合适的位置。
代码如下:
def insertsort(seq):
len1 = len(seq)
for i in range(1,len1):
sortI=i
for j in range(i-1,-1,-1):
if seq[i]>=seq[j]:
break
else:
seq[i],seq[j] = seq[j],seq[i]
i=j
i = sortI
if __name__ == '__main__':
seq= [3,7,4,3.5,2,14,9,7.4,34,21,65,78,36,64,32,0,2.3]
insertsort(seq)
print 'insertsort=',seq
另一个稍微修改内循坏代码如下:
def insertsort2(seq):
len1 = len(seq)
for i in range(1,len1):
#key = seq[i]
j = i-1
while j >= 0 and seq[j] > seq[i]:
seq[i],seq[j] = seq[j],seq[i]
i=j
j-=1
pass
结果如下;
C:\Python27\python.exe E:/MyProject/python2.7/datastructure/sort/insertsort.py
insertsort= [0, 2, 2.3, 3, 3.5, 4, 7, 7.4, 9, 14, 21, 32, 34, 36, 64, 65, 78]
Process finished with exit code 0