Python排序搜索基本算法之插入排序实例分析
作者:littlethunder 时间:2023-12-28 14:20:25
本文实例讲述了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)
运行结果:
PS:这里再为大家推荐一款关于排序的演示工具供大家参考:
在线动画演示插入/选择/冒泡/归并/希尔/快速排序算法过程工具:
http://tools.jb51.net/aideddesign/paixu_ys
希望本文所述对大家Python程序设计有所帮助。
来源:http://blog.csdn.net/littlethunder/article/details/9399957
标签:Python,算法,插入排序
![](/images/zang.png)
![](/images/jiucuo.png)
猜你喜欢
python中如何使用正则表达式提取数据
2023-12-09 17:24:21
![](https://img.aspxhome.com/file/2023/7/86327_0s.png)
python中filter,map,reduce的作用
2023-12-18 11:13:15
python实现图像最近邻插值
2023-02-01 00:03:34
![](https://img.aspxhome.com/file/2023/3/93563_0s.jpg)
python错误:AttributeError: 'module' object has no attribute 'setdefaultencoding'问题的解决方法
2021-09-15 16:28:22
教你在MySQL 5.0以上版本中配置主从库
2009-01-04 13:17:00
CSS文件的编码要和页面的编码相一致
2010-06-06 13:59:00
为什么MySQL选择Repeatable Read作为默认隔离级别
2024-01-13 01:09:26
![](https://img.aspxhome.com/file/2023/6/122936_0s.jpg)
python3应用windows api对后台程序窗口及桌面截图并保存的方法
2023-10-23 12:29:19
浅析SQL Server 聚焦索引对非聚集索引的影响
2024-01-16 19:19:44
![](https://img.aspxhome.com/file/2023/0/94470_0s.png)
vue+php实现的微博留言功能示例
2023-11-18 01:47:02
python SVD压缩图像的实现代码
2023-04-18 18:23:30
![](https://img.aspxhome.com/file/2023/6/86496_0s.jpg)
浅谈python写入大量文件的问题
2021-12-07 00:44:00
python 监控服务器是否有人远程登录(详细思路+代码)
2022-05-16 04:08:26
![](https://img.aspxhome.com/file/2023/8/109628_0s.png)
MySQL服务器 IO 100%的分析与优化方案
2024-01-24 08:34:10
![](https://img.aspxhome.com/file/2023/3/118483_0s.png)
python中asyncio异步编程学习
2022-10-20 06:19:37
python-docx如何缩进两个字符
2022-07-04 15:56:45
![](https://img.aspxhome.com/file/2023/5/124925_0s.png)
简单解析PHP程序的运行流程
2023-06-22 07:35:41
![](https://img.aspxhome.com/file/2023/1/55481_0s.gif)
SELECT...INTO的具体用法
2024-01-29 02:20:43
python数据类型之间怎么转换技巧分享
2023-09-04 02:38:42
![](https://img.aspxhome.com/file/2023/0/65040_0s.png)
python k-近邻算法实例分享
2022-03-26 14:47:17