我的插入排序算法的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
,以便在必要时向前移动列表中的第一个值。