我的插入排序算法的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
,以便你可以在必要时转移列表中的第一个值。
问题出在这个声明中
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)