插入排序算法

2024-09-30 10:36:27 发布

您现在位置: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)

Tags: and代码in算法列表forlen排序
2条回答

问题出在这句话上

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)

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

相关问题 更多 >

    热门问题