python - 插入排序算法因一个错误而关闭
问题描述
我的插入排序算法的 Python 代码几乎可以工作,但由于某种原因,我的列表的第一项没有排序 - 有人可以告诉我问题出在哪里吗?
listToBeSorted = [7,2,4,3,6,5,1]
for pointer in range(1, len(listToBeSorted )):
itemToBeInserted = listToBeSorted[pointer]
currentIndex = pointer - 1
while listToBeSorted[currentIndex] > itemToBeInserted and currentIndex > 0:
listToBeSorted[currentIndex + 1] = listToBeSorted[currentIndex]
currentIndex -= 1
listToBeSorted[currentIndex + 1] = itemToBeInserted
print(listToBeSorted)
解决方案
while
您的代码过早结束循环。而不是currentIndex > 0
, 您想要currentIndex >= 0
,以便您可以在必要时将列表中的第一个值向前移动。
推荐阅读
- javascript - 关闭父窗口/停止传播
- node.js - 如何使用 Express 将 powershell 命令结果推送到 NodeJs 中的 json 响应?
- entity-framework-6 - 如何从具有实体框架的 DbDataReader 加载每个层次结构类型的表?
- apache-flink - 来自目录的 Apache Flink 流式处理文件
- r - 无法在 R 版本 3.5 - Windows 10 上安装 R 的 data.table
- c# - 使用 TextInfo.ListSeparator 追加字符串数组
- python - 将列索引字符串附加到 DataFrame 列
- wpf - WPF - 如何在窗口的代码隐藏中访问公共字段的类型
- c# - 在 IIS 中发布后,在 C# ASP.net 中执行 .Bat 文件不起作用
- snowflake-cloud-data-platform - Snowsql 两位数世纪开始日期转换问题