简体   繁体   中英

Bubble sort not correctly sorting list

I've written the following bubble sort, why won't it output the correct results?

number = [8,6,4,5,7]
while x == True:
    for i in range(0,len(number)-1):
       if number[i]>number[i+1]:
     x == True 
     number[i],number[i+1]=number[i+1],number[i]
  x = False   
print(number)
  1. You're setting x = False at the end of your while loop, so the loop only ever run once, set it on the first line of your loop.
  2. You use x == True instead of x = True so your loop will only run once as x remains False .
  3. You don't set x = True before your loop starts, so it won't even enter the loop.
  4. Your indentation is incorrect (this is probably from the copying your code here as otherwise it wouldn't run at all).

Changing all this will result in your code working:

>>> x = True
>>> number = [8,6,4,5,7]
>>> while x == True:
...     x = False
...     for i in range(0,len(number)-1):
...        if number[i]>number[i+1]:
...            x = True
...            number[i],number[i+1]=number[i+1],number[i]
...
>>> print(number)
[4, 5, 6, 7, 8]

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