gpt4 book ai didi

python - 插入排序算法差一错

转载 作者:塔克拉玛干 更新时间:2023-11-03 04:37:37 25 4
gpt4 key购买 nike

我的插入排序算法的 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,以便您可以在必要时向前移动列表中的第一个值。

关于python - 插入排序算法差一错,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/55039570/

25 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com