插入排序算法关闭一个错误

问题描述 投票:1回答:2

我的插入排序算法的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)
python algorithm sorting
2个回答
1
投票

你的代码太早结束了while循环。而不是currentIndex > 0,你想要currentIndex >= 0,以便你可以在必要时转移列表中的第一个值。


1
投票

问题出在这个声明中

while listToBeSorted[currentIndex] > itemToBeInserted and currentIndex > 0

应该是

while listToBeSorted[currentIndex] > itemToBeInserted and currentIndex > -1

如果currentIndex总是大于0,那么列表的第一个元素永远不会被排序,因为列表中的项目不会插入列表的开头。

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 > -1:
       listToBeSorted[currentIndex + 1] = listToBeSorted[currentIndex]
       currentIndex -= 1
    listToBeSorted[currentIndex + 1] = itemToBeInserted

print(listToBeSorted)
© www.soinside.com 2019 - 2024. All rights reserved.