正在尝试创建插入排序,但收到错误。。。你知道吗
我真的不知道为什么会这样。它总是倾向于错过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
在循环过程中,您将从
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情况下,您将覆盖而不是插入值。你知道吗
相关问题 更多 >
编程相关推荐