本文实例讲述了Python排序搜索基本算法之插入排序。分享给大家供大家参考,具体如下:
插入排序生活中非常常见,打扑克的时候人的本能就在用插入排序:把抽到的一张插入到手上牌的正确位置上。有两种插入排序方法,一种基于比较,另一种基于交换。代码如下:
1.基于比较的插入排序:
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
|
# coding:utf-8
def insertionSort(seq):
length = len (seq)
for i in range ( 1 ,length):
tmp = seq[i]
for j in range (i, 0 , - 1 ):
if seq[j - 1 ]>tmp:
seq[j] = seq[j - 1 ]
else :
j + = 1
break
seq[j - 1 ] = tmp
if __name__ = = '__main__' :
print ( "服务器之家测试结果:" )
seq = [ 8 , 6 , 4 , 9 , 7 , 3 , 2 , - 4 , 0 , - 100 , 99 ]
insertionSort(seq)
print (seq)
|
运行结果:
2.基于交换的插入排序:
1
2
3
4
5
6
7
8
9
10
11
12
13
14
|
# coding:utf-8
def insertionSort2(seq):
length = len (seq)
for i in range ( 1 ,length):
for j in range (i, 0 , - 1 ):
if seq[j]<seq[j - 1 ]:
seq[j],seq[j - 1 ] = seq[j - 1 ],seq[j]
else :
break
if __name__ = = '__main__' :
print ( "服务器之家测试结果:" )
seq = [ 3 , 5 , 9 , 8 , 4 , 2 , 1 , 0 , - 6 , 12 , - 8 ]
insertionSort2(seq)
print (seq)
|
运行结果:
希望本文所述对大家Python程序设计有所帮助。
原文链接:http://blog.csdn.net/littlethunder/article/details/9399957