python中的插入排序的简单用法
作者:十一 时间:2023-09-30 07:57:51
现在大家学习python掌握内容了解太多太多,但是最重要的不是掌握了解算法的使用,而是了解算法原理远比使用算法命令更重要,现在大家了解算法应该都不低于5种了吧,比如排序算法、冒泡算法、归并算法等等,那对本期主题插入算法有过了解吗?如果没有了解的小伙伴可以跟着小编一起来了解学习。
插入排序简介:
将列表分为有序区和无序区两个部分,最初有序区只有一个元素,即第一个元素。
然后每次从无序区选择一个元素,插入到有序区中,直到无序区为空。
运行图示:
实现代码:
# 选择排序 O(n2)
def insert_sort(li):
for i in range(1, len(li)):
tmp = li[i]
j = i - 1
while j >= 0 and li[j] > tmp:
li[j + 1] = li[j]
j -= 1
li[j+1] = tmp
扩展实例代码:
# -*- coding: utf-8 -*-
'''
插入排序:
类似于摸牌,从牌堆中摸一张牌,和手中现有手牌比较。若大则放右边,小放左边。
''
def insert_sort(input_list):
if len(input_list)<=1:
return input_list
for right in range(1,len(input_list)): # 开始从牌堆中摸牌
val = input_list[right] # 当前摸牌的值
for left in range(0,right): # 循环和手中牌进行比较
if val <= input_list[left]: # 若<最左边的牌了
input_list[left+1:right+1]=input_list[left:right]
input_list[left]=val
break
return input_list
if __name__ == '__main__':
pre_list = [1,6,3,3,7]
res = insert_sort(pre_list)
print(res)
来源:https://www.py.cn/jishu/jichu/23053.html
标签:python,插入排序
![](/images/zang.png)
![](/images/jiucuo.png)
猜你喜欢
Python进程间的通信一起来了解下
2022-10-27 01:41:30
![](https://img.aspxhome.com/file/2023/1/101331_0s.png)
ERROR 1862 (HY000): Your password has expired. To log in you must change it using a .....
2024-01-12 19:56:51
![](https://img.aspxhome.com/file/2023/0/81040_0s.png)
地图网站的需求功能与体验
2009-03-01 11:15:00
![](https://img.aspxhome.com/file/UploadPic/20093/1/01_b-87s.jpg)
对Python中plt的画图函数详解
2023-08-16 08:49:07
Python实现爬取亚马逊数据并打印出Excel文件操作示例
2021-09-10 05:10:36
![](https://img.aspxhome.com/file/2023/3/105203_0s.png)
Python基于PyGraphics包实现图片截取功能的方法
2023-08-05 21:55:51
Vue实现无限加载瀑布流
2024-05-09 15:23:16
![](https://img.aspxhome.com/file/2023/1/126431_0s.gif)
Python区块链创世块创建教程
2023-10-10 06:25:52
JavaScript ES6语法中let,const ,var 的区别
2024-05-09 15:06:49
MySQL授权命令grant的使用方法小结
2024-01-22 14:09:22
Div+CSS布局入门教程
2007-09-13 12:52:00
![](https://img.aspxhome.com/file/uploadpic/20079/13/20079131325394.gif)
pandas 实现某一列分组,其他列合并成list
2022-06-12 13:49:21
![](https://img.aspxhome.com/file/2023/8/95578_0s.jpg)
Python中操作符重载用法分析
2023-04-05 12:34:51
Golang的继承模拟实例
2024-05-08 10:23:14
Response.Flush的用法
2010-04-08 12:54:00
SQL Server 数据库基本操作语句总结
2024-01-18 05:12:06
Django app配置多个数据库代码实例
2023-06-11 09:11:25
从mysql读写分离着手提升服务器性能
2024-01-22 06:56:10
![](https://img.aspxhome.com/file/2023/8/65298_0s.png)
Python中赋值的含义及说明
2023-01-05 23:11:38
![](https://img.aspxhome.com/file/2023/4/120574_0s.png)
Opera下的max-width BUG
2010-06-26 12:51:00
![](https://img.aspxhome.com/file/UploadPic/20106/26/2010626125629969s.png)