我为插入排序算法编写的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)
问题出在这句话上
哪个应该是
如果
currentIndex
始终大于0,则列表的第一个元素永远不会被排序,因为列表中的任何项都不会插入到列表的开头代码过早地结束了
while
循环。您需要的不是currentIndex > 0
,而是currentIndex >= 0
,这样您就可以在必要时向前移动列表中的第一个值相关问题 更多 >
编程相关推荐