I'm writing in python and I thought I might try to use recursion to create a bubble sort. My idea is that, since the rightmost element is always sorted after every iteration (list[-1])
, I add that element to another call of bubblesort for the rest of my elements (bubbleSort(list[:-1]))
. Here is my code:
def bubbleSort(list):
sorted = True
i = 0
if len(list) <= 1:
return list
while i < len(list) - 1:
if list[i] > list[i+1]:
temp = list[i+1]
list[i+1] = list[i]
list[i] = temp
sorted = False
i = i + 1
if sorted:
return list
else:
endElement = list[-1]
return bubbleSort(list[:-1]) + [endElement]
However, it only ever returns the first iteration of the sort, despite it running through every iteration (I used print inside of the code to see if it was running). The recursion is necessary: I know how to do it without it. It's just the recursion part that messes up anyways.