首页 > 解决方案 > 插入排序算法因一个错误而关闭

问题描述

我的插入排序算法的 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)

标签: pythonalgorithmsorting

解决方案


while您的代码过早结束循环。而不是currentIndex > 0, 您想要currentIndex >= 0,以便您可以在必要时将列表中的第一个值向前移动。


推荐阅读