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)
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.x == True
instead of x = True
so your loop will only run once as x
remains False
.x = True
before your loop starts, so it won't even enter the loop.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.