我正在练习用不同语言编写各种排序函数。我用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
这里的问题看起来就像是你的索引的使用,这样,你必须确保'i'和'i + 1'都小于'len(someList)',因为在最后一种情况下,比如你的列表len是3,当i是2时,i + 1是3并且是一个超出范围的索引。 – Copperfield