简体   繁体   中英

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

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

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM