2016-10-10 48 views
0

尝试创建插入排序但收到错误...插入排序不工作 - 列表索引超出范围

不知道为什么会发生这种情况。它总是倾向于错过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 
+0

这些与您的错误无关。这已经在答案中解释了,但我想补充一句,'Tsorted.append(items.pop(items [0]))'等于你在这两行中做的事情。此外,'Tsorted [-1]'会给你与'Tsorted [len(Tsorted)-1]'相同的结果 – Lafexlos

回答

1

第一件事:你去除,你是这里的循环中遍历数组的项目:items.remove(items[i])。这通常不是一个好主意。

二:这种算法没有实现插入排序,即使你修复缺失的问题。您应该查看算法,例如这里Insertion sort in Wikipedia。 Thre是找到合适的插入位置所需的另一个循环。

第三:在其他情况下,您将覆盖而不是插入值。

0

您要删除在循环的过程中,从items元素;因此,i可能会成为原始items中的有效索引值,但不再缩写。

如果您需要从items删除元素,它看起来像你应该等到循环结束。

0

那是因为你打电话tems.remove()。当我= 4和items=[37, 46, 90, 50]时,您的代码失败。

所以他们已经没有任何一种元素与索引43因为索引以0

0

range(0,len(items)将只计算第一次你的代码打开始的for循环,在此状态len(list) = 8。这意味着你将会迭代

for i in [0,1,2,3,4,5,6,7] 
    #Do stuff... 

但是在同一时间你从每个循环的列表中删除项目。所以打我= 4时,你有你的迭代循环4次,你的长度item -list只有4,这意味着items[4] 不再存在。