2015-12-22 46 views
0

我正在练习用不同语言编写各种排序函数。我用python写了一个使用递归调用的冒泡排序,但我不知道如何正确地终止递归。正如我现在的程序正确排序,但超出了我的列表参数,并触发一个错误:IndexError:列表索引超出范围(在第29行)[即bubblesort(randomList)]python中的递归调用导致IndexError:列表索引超出范围

import random 
#create a list of 10 random ints between 0-99 to be sorted 
def makeRandomList(): 
    unsortedList=[] 
    for i in range(10): 
     unsortedList.append(random.randrange(100)) 
    print unsortedList 
    return unsortedList 


def bubblesort(randomList): 
    i=0 
    while i<=len(randomList): 
     if randomList[i] > randomList[i+1]: 
      randomList[i], randomList[i+1] = randomList[i+1], randomList[i] 
      i+=1 
      if i<len(randomList): 
       bubblesort(randomList) 
      else: break 
     else: 
      i+=1 
      #for testing purposes 
      print randomList 
    return randomList 


randomList=makeRandomList() 
sortedList=bubblesort(randomList) 
print "sorted list: ", sortedList 
+0

这里的问题看起来就像是你的索引的使用,这样,你必须确保'i'和'i + 1'都小于'len(someList)',因为在最后一种情况下,比如你的列表len是3,当i是2时,i + 1是3并且是一个超出范围的索引。 – Copperfield

回答

1

此错误是从最初发布的代码编辑的。

这条线是做你期望的吗?

randomList[-i]<[-(i+1)] 

在这里,你只是与元件randomlist[-i]比较[ - (I + 1)]。 [ - (i + 1)]只是一个整数而不是randomlist的元素。它应该是

randomList[-i]<randomlist[-(i+1)] 

如果您试图比较列表的元素。

更有效的方式来创建大小为10的随机列表:

当创建一个整数无序列表,利用random.sample()这样你就不会浪费时间和空间的迭代。在你的情况下,random.sample(range(100), 10).

0

你的inOrder功能不起作用。我是一个变量作用域的函数,因此在开头设置i + = 1意味着它不会在下一次递归调用中设置为该值。

0

你可以用它来增加你的递归调用量:

sys.setrecursionlimit(10000) 

我还建议试图避免递归的方法,你的理由。

您应该通过列表来获取最小值和最大值,然后尝试并预测值的位置。因此,如果列表中的选定项目少于100,则将其置于位置10. 或者您可以检查它之前的值是大于还是小于它,如果小于它,则将它设置为它之后的值: )例如:

Age = [10,11,20,9,10,2,1,3] 

for X in range(0, len(Age)): 
    if X < len(Age) - 1: 
     if Age[X] > Age[X + 1]: 
      Temp = Age[X + 1] 
      Age[X + 1] = Age[X] 
      Age[X] = Temp 

print(Age) 

输出是:[10, 11, 9, 10, 2, 1, 3, 20]

你会希望有一个while循环surounding for循环:)

1

我解决我的问题。我的索引运行在列表的末尾(也就是说,当我是len(randomList)时,我的程序正在寻找len(randomList + 1),它并没有在基本情况下终止,因为然后while循环是我< = LEN(randomList)时,它应该是我<(LEN(randomList)-1),这是正确的解决办法:

def bubblesort(randomList): 
    i=0 
    while i<(len(randomList)-1): 
     if randomList[i] > randomList[i+1]: 
      randomList[i], randomList[i+1] = randomList[i+1], randomList[i] 
      i+=1 
      if i<(len(randomList)-1): 
       bubblesort(randomList) 
      else: break 
     else: 
      i+=1 
      print randomList 
    return randomList 
+0

你的递归定义的方式'inorder'是不正确的。 – imp9

相关问题