嘗試創建插入排序但收到錯誤...插入排序不工作 - 列表索引超出範圍
不知道爲什麼會發生這種情況。它總是傾向於錯過37藏漢
numbers = [45,56,37,79,46,18,90,81,50]
def insertionSort(items):
Tsorted = []
Tsorted.append(items[0])
items.remove(items[0])
for i in range(0,len(items)):
print (Tsorted)
if items[i] > Tsorted[len(Tsorted)-1]:
Tsorted.append(items[i])
else:
Tsorted[len(Tsorted)-2] = items[i]
items.remove(items[i])
insertionSort(numbers)
錯誤:
if items[i] > Tsorted[len(Tsorted)-1]:
IndexError: list index out of range
這些與您的錯誤無關。這已經在答案中解釋了,但我想補充一句,'Tsorted.append(items.pop(items [0]))'等於你在這兩行中做的事情。此外,'Tsorted [-1]'會給你與'Tsorted [len(Tsorted)-1]'相同的結果 – Lafexlos