So I defined a function for bubble sorting but when I try to run it I just get a blank console window. I feel like its something really stupid like a syntax error but I can't pin it down. Here is the code:
def bubble(arr):
swap = True
while (swap == True):
swap = False
for i in range(len(arr)-1):
temp = arr[i]
if arr[i]> arr[i+1]:
temp = arr[i+1]
arr[1] = arr[i+1]
swap = True
array = ["AB","AAB","AAA"]
print (bubble(array))
input()
Here is a bubble function that will more likely work.
def bubble(arr):
swap = True
while (swap == True):
swap = False
for i in range(len(arr)-1):
if arr[i]> arr[i+1]:
arr[i], arr[i+1] = arr[i+1], arr[i]
swap = True
return arr
There are various issues in your original bubble function.
print(bubble(array))
will always output None
swap = True
statement was ill-placed, and was executed at each step of your while loop, resulting in infinite looparr[1] = arr[i+1]
instead of arr[i] = arr[i+1]
, and forgot the second part of swapping. In python, you can swap two values without the need of a temp
variable, which is what I've done.