我试图创建一个由7个随机生成的数字组成的数组,然后使用插入排序方法将这些数字从最小到最大排序。我看了几个以前回答的主题,因为这是一个非常常见的问题,但每个用户都有非常不同的代码给我,这让我想知道我哪里做错了。你知道吗
import random # importing the random module
arrayInsertion = []
for i in range (7): # 7 different numbers
arrayInsertion.append(random.randint (1,10))
for i in range (1,7):
while i > 0 and arrayInsertion [i+1] > arrayInsertion [i]:
arrayInsertion [i] = arrayInsertion [i-1]
i = i - 1
print (arrayInsertion)
运行此代码时,我收到以下错误消息:
Traceback (most recent call last): File "C:\Users\Ben\Desktop\insertion sort.py", line 8, in while i > 0 and arrayInsertion [i+1] > arrayInsertion [i]: IndexError: list index out of range
也可以只使用内置的.sort()方法
问题是
arrayInsertion[i + 1]
当i = 7
然后i
超出界限时,因为列表中只有7
个元素。您也不记得当前值和索引。你知道吗正确地得出:
为便于将来使用,请考虑将其打包到函数
def insertion_sort(a)
。你知道吗因此它将抛出索引器:列表索引超出范围
相关问题 更多 >
编程相关推荐