Search code examples
pythonlistsortingbubble-sort

Print statement failing to output on terminal inside nested loops/function


This is my first question ever, so forgive me if I do something wrong.

I used Visual Studio to code a simple sorting algorithm this time, but I'm having a issue with it. I need to print the list of numbers not only to check if it is sorting, but also to see the final product. However, the terminal is not showing anything. Printing outside of the function, which has nested loops, works fine however. I tried to print a string as well, but nothing comes out. I assume I'm missing something simple, but I thought I would ask here since I've never asked a question here before. Thanks in advance. If there's any advice on asking questions, please don't hesitate to say.

bunny = 0
turtle = 0
temp = 0
sequence = [2, 8, 7, 1, 4]


def bubblesort():

    for x in sequence:
        turtle = sequence[x]
        for y in sequence:
            bunny = sequence[y]
            if sequence[y] < sequence[x]:
                temp = sequence[y]
                sequence[y] = sequence[x]
                sequence[x] = temp
                temp = 0
    return print(sequence)


print(sequence)

Solution

  • Following on the comments saying the for loop won't iterate through indices, as expected, you can obtain the index through the "enumerate" method instead. I also made some refactoring: you don't need to declare bunny, turtle, temp at the beginning of the code, and I made it so bubblesort takes a vector as parameter instead of edit a global one.

    sequence = [2, 8, 7, 1, 4]
    
    def bubblesort(seq):
        for x, turtle in enumerate(seq):
            for y, bunny in enumerate(seq):
                if bunny < seq[x]:
                    temp = bunny
                    seq[y] = seq[x]
                    seq[x] = temp
        print(seq)
    
    bubblesort(sequence)