插入排序错误列表索引

2024-10-02 22:37:33 发布

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

我试图创建一个由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


Tags: and方法代码用户inimport主题for
3条回答

也可以只使用内置的.sort()方法

问题是arrayInsertion[i + 1]i = 7然后i超出界限时,因为列表中只有7个元素。您也不记得当前值和索引。你知道吗

for i in range(1, len(arrayInsertion)):
    curr = arrayInsertion[i]
    pos = i
    while pos > 0 and arrayInsertion[pos - 1] > curr:
        arrayInsertion[pos] = arrayInsertion[pos - 1]
        pos -= 1
    arrayInsertion[pos] = curr

正确地得出:

[5, 5, 5, 6, 6, 8, 9]

为便于将来使用,请考虑将其打包到函数def insertion_sort(a)。你知道吗

for i in range(1,7) 

Above line of code will produce 1 to 6 sequentially (1,2,3,4,5,6)

while  i > 0 and arrayInsertion [i+1] > arrayInsertion [i]

arrayInsertion [i+1] in above line in try to access arrayInsertion[7] for i = 6 which is not present

因此它将抛出索引器:列表索引超出范围

相关问题 更多 >