Reputation: 79
The objective of this is to take a list of positive integers and sort them using bubble sort. It works whenever you input a list that does not require a single element to be moved more than once. How do I get it to move an element more than once?
For example, inputting [3,5,4,6,7] works but [10,9,8,7,6] does not.
def bubbleSort(lis):
swapped = True
while swapped:
swapped = False
for i in range(0,len(lis)-1):
if lis[i] > lis[i + 1] or lis[i] == lis[i+1]:
switch = lis[i]
lis[i] = lis[i+1]
lis[i+1] = switch
return lis
print(lis)
print(bubbleSort([3,5,4,6,7]))
print(bubbleSort([10,9,8,7,6]))
Upvotes: 0
Views: 94
Reputation: 41
You should not set swapped to 'false' when you enter the while loop, because then you make only one iteration of the loop. You should exit the loop when there are no more swaps when you iterate over the entire list.
Upvotes: 0
Reputation: 77850
The problem is that you return after only one pass through the list. Wait until swapped
is False
.
Also, you must set swapped
when you make a switch.
swapped = True
while swapped:
swapped = False
for i in range(0,len(lis)-1):
if lis[i] > lis[i + 1] or lis[i] == lis[i+1]:
swapped = True
switch = lis[i]
lis[i] = lis[i+1]
lis[i+1] = switch
return lis
I removed the print
statement because you can never reach it, and that should be the job of the calling program.
Upvotes: 3