一图胜千言,插入排序的核心逻辑如下:

  • 将数据分成两半,前一半是已排好序的,后一半是待排序的
  • 每次取后一半中的第一个数,在已排序的一半中,逆序依次比较,找到要插入的位置
  • 记录插入的位置,在最后判断是否需要插入即可

实现代码:


def insertionSort(a:list):
for i in range(1,len(a)):
value = a[i]
insert_index = -1 for j in range(i-1,-1,-1):
if value< a[j]:
a[j+1] = a[j]
insert_index = j
else:
break
if insert_index !=-1:
a[insert_index] = value return a

思考:

为什么插入排序比冒泡排序更常用

关键在于赋值操作,冒泡排序需要3次,而插入排序只需要1次

最新文章

  1. performSelector和performSelectorInBackground
  2. 机器学习相关的Awesome系列
  3. leveldb 学习笔记之VarInt
  4. psp工具需求分析
  5. 怎样查看linux版本
  6. WPF 屏蔽Alt+F4强制退出
  7. AjaxHelper创建的ajax无效,JQuery直接方法post有效,原来是Microsoft.jQuery.Unobtrusive.Ajax错误,NuGet解决
  8. c++优先级
  9. C#新DataColumn类Type生成的方法类型参数
  10. Bombing HDU, 4022(QQ糖的消法)
  11. vijos1090题解
  12. MySQL字符集设置—MySQL数据库乱码问题
  13. node实现jsonp跨域
  14. Struts2配置。
  15. Ubuntu/Unity中更改窗口修饰键Alt为Super
  16. 破解WPA工具Tkiptun-ng
  17. [Ubuntu] LightDM 轻量级桌面显示管理器
  18. HLSL-高级着色语言简介【转】
  19. ajax跨域调用webservice例子
  20. 项目Beta冲刺(团队)第六天

热门文章

  1. flutter SnackBar异常Another exception was thrown: Scaffold.of() called with a context that does not contain a Scaffold
  2. 【MM系列】SAP MM模块-货物移动对标准价的影响
  3. Flask(六)—— 自定义session
  4. ubuntu server安装的一些坑
  5. SpringBoot项目快速启动停止脚本
  6. Deepin15.10 python3安装、更新pip
  7. [2019徐州网络赛J题]Random Access Iterator
  8. sudo pip install -i http://pypi.douban.com/simple/ --trusted-host=pypi.douban.com/simple ipython
  9. 数学: HDU Co-prime
  10. Hangfire