Search code examples
pythonbubble-sort

Why does my program not output anything in the command window when I run it?


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()

Solution

  • 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.

    1. Your function does not return anything, so print(bubble(array)) will always output None
    2. Your second swap = True statement was ill-placed, and was executed at each step of your while loop, resulting in infinite loop
    3. you wrote arr[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.