Search code examples
pythonarrayspython-3.xif-statementbubble-sort

When running my function my if statement is not running


I am trying to make a simple bubble sort, and the if statement i'm using to sort the numbers in my array is not running. Can anybody help me get this to run?

Here is my code:

def Bubble( a ):
    Flag = False
    while not Flag:
        Flag = True
        for i in range(0, len(a), -1):
            if a[i] > a[i+1]: #this if statement isn't running
                a[i], a[i + 1] = a[i + 1], a[i]
                print("hi")
                Flag = False



def main():
    a = GRN(10)
    acopy = a[:]
    Bubble(a)
    acopy.sort()
    print(a==acopy)
    print(a)
    print(acopy)


main()

Solution

  • range(0, len(a), -1) is always an empty list, because the step is negative. It is not the if statement to blame, but the for loop. What you need is range(len(a)-1).