插入排序不工作列表索引超出范围

2024-06-25 23:32:59 发布

您现在位置:Python中文网/ 问答频道 /正文

正在尝试创建插入排序,但收到错误。。。你知道吗

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

Tags: inforlenifdef错误itemsrange
3条回答

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

如果需要从items中删除元素,那么看起来应该等到循环完成。你知道吗

那是因为你打电话给tems.remove()。当i=4且items=[37, 46, 90, 50]时,代码将失败。你知道吗

因此它们已经没有索引为4的元素,而是索引为3,因为索引从0开始。你知道吗

第一件事:从循环中迭代的数组中删除项:items.remove(items[i])。这通常不是个好主意。你知道吗

第二:这个算法不实现插入排序,即使你解决了删除问题。你应该回顾一下算法,例如这里Insertion sort in Wikipedia。这是找到正确插入位置所需的另一个循环。你知道吗

第三:在else情况下,您将覆盖而不是插入值。你知道吗

相关问题 更多 >