Posted in Python onDecember 11, 2017
本文实例讲述了Python排序搜索基本算法之插入排序。分享给大家供大家参考,具体如下:
插入排序生活中非常常见,打扑克的时候人的本能就在用插入排序:把抽到的一张插入到手上牌的正确位置上。有两种插入排序方法,一种基于比较,另一种基于交换。代码如下:
1.基于比较的插入排序:
# 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.基于交换的插入排序:
# 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排序搜索基本算法之插入排序实例分析
- Author -
littlethunder声明:登载此文出于传递更多信息之目的,并不意味着赞同其观点或证实其描述。
Reply on: @reply_date@
@reply_contents@