插入排序不起作用 - 列表索引超出范围

时间:2016-10-10 10:54:50

标签: python python-2.7 insertion-sort

尝试创建插入排序但收到错误...

不知道为什么会这样。它总是倾向于错过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

4 个答案:

答案 0 :(得分:1)

首先:您要从循环中迭代的数组中移除项目:items.remove(items[i])。这通常不是一个好主意。

第二:即使您修复了删除问题,此算法也不会实现插入排序。您应该查看算法,例如这里Insertion sort in Wikipedia。 Thre是找到正确插入位置所需的另一个循环。

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

答案 1 :(得分:0)

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

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

答案 2 :(得分:0)

那是因为您正在调用tems.remove()。当i = 4且items=[37, 46, 90, 50]时,您的代码会失败。

所以他们已经没有索引为4但是3的元素,因为索引从0开始。

答案 3 :(得分:0)

range(0,len(items)只会在您的代码首次触及for循环时计算,状态为len(list) = 8。这意味着你将重复

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

但同时您在每个循环中从列表中删除项目。因此,当命中i = 4时,你已经迭代了你的循环4次而你的长度item - list只有4,这意味着items[4]  不再存在。

相关问题