【问题标题】:Insertion sort error list index插入排序错误列表索引
【发布时间】:2017-08-09 14:42:45
【问题描述】:

我正在尝试创建一个由 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(最近一次调用最后一次): 文件“C:\Users\Ben\Desktop\insertion sort.py”,第 8 行,在 当 i > 0 且 arrayInsertion [i+1] > arrayInsertion [i] 时: IndexError: 列表索引超出范围

【问题讨论】:

  • 当您打算使用i-1时,您使用的是i+1吗?

标签: python insertion-sort insertion


【解决方案1】:

问题是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)

【讨论】:

    【解决方案2】:

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

    【讨论】:

      【解决方案3】:
      for i in range(1,7) 
      

      以上代码行会依次产生1到6(1,2,3,4,5,6)

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

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

      所以它会抛出IndexError: list index out of range

      【讨论】:

        【解决方案4】:
        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
        

        【讨论】:

        • 欢迎来到Stack Overflow。请查看How to Answer!仅代码的答案不如解释它们如何工作以及为什么它们比 OP 发布的代码更好的答案有用。
        猜你喜欢
        • 1970-01-01
        • 1970-01-01
        • 2021-11-07
        • 1970-01-01
        • 1970-01-01
        • 1970-01-01
        • 1970-01-01
        • 2018-04-02
        • 2021-05-02
        相关资源
        最近更新 更多