2017-03-17 139 views
0

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

+0

当你的意思是使用'i-1'时,你是否在使用'i + 1'? – Blckknght

回答

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)

0
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 
+1

欢迎来到[so]。请查看[回答]!仅有代码的答案比解释他们如何工作以及为什么他们比OP发布的代码更好的问题没有那么有用。 – TemporalWolf

0

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

0
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

所以它会抛出IndexError:列表索引超出范围