Python 插入排序错误列表索引

Python 插入排序错误列表索引,python,insertion-sort,insertion,Python,Insertion Sort,Insertion,我试图创建一个由7个随机生成的数字组成的数组,然后使用插入排序方法将这些数字从最小到最大排序。我已经浏览了几个以前回答过的主题,因为这是一个非常常见的问题,但是每个用户对我来说都有非常不同的代码,这让我想知道我哪里出了问题 import random # importing the random module arrayInsertion = [] for i in range (7): # 7 different numbers arrayInsertion.append(rando

我试图创建一个由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)
运行此代码时,我收到以下错误消息:

回溯(最近一次呼叫最后一次): 文件“C:\Users\Ben\Desktop\insertion sort.py”,第8行,在 而i>0和arrayInsertion[i+1]>arrayInsertion[i]: 索引器:列表索引超出范围


问题是
arrayinservation[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插入式排序(A) .

,您也可以只使用内置的.SoTo()方法< /P> 上述代码行将按顺序生成1到6(1,2,3,4,5,6)

上一行中的arrayInsertion[i+1]尝试访问i=6的arrayInsertion[7],该选项不存在


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

当您打算使用
i-1
时,您是否正在使用
i+1
?欢迎使用。请复习!只有代码的答案没有解释它们是如何工作的以及为什么它们比张贴的代码更好的答案有用。
def insert_sort(list_input):
    for unsorted_id in range(len(list_input)):
        element = list_input[unsorted_id]
        sorted_id = unsorted_id - 1
        while sorted_id >= 0 and element > list_input[sorted_id]:
            list_input[sorted_id + 1] = list_input[sorted_id]
            sorted_id -= 1
        list_input[sorted_id + 1] = element
    return list_input
for i in range(1,7) 
while  i > 0 and arrayInsertion [i+1] > arrayInsertion [i]