I am practicing writing various sort functions in different languages. I wrote a bubble sort in python using a recursive call but I don't know how to properly terminate the recursion. As I have it now the program sorts correctly but extends beyond the parameters of my list and triggers an error: IndexError: list index out of range (on line 29) [i.e. bubblesort(randomList)]
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
iandi+1both are less thanlen(someList)because in last case, say your list len is 3, when i is 2, i+1 is 3 and is a index out of range...