简体   繁体   中英

Bubble Sort Python sorting only once

Can anyone help me in identifying the error in this program for bubble sort?

def bsort(a):
    for i in range (0, len(a)-1):
        for j in range(i):
            if a[j]> a[j+1]:
                temp = a[j]
                a[j] = a[j+1]
                a[j+1] = temp

num = [1,2,6,5,7,2,5,9]
bsort(num)
print(num)

It sorts the list only once.

更改外循环中的范围:

for i in range (0, len(a)):

Minor issues in for loop.

def bsort(a):
    for i in range (0, len(a)-1):
        for j in range(len(a)-2): ## updated here
            if a[j]> a[j+1]:
                temp = a[j]
                a[j] = a[j+1]
                a[j+1] = temp

num = [1,2,6,5,7,2,5,9]
bsort(num)
print(num)

Output is [1, 2, 2, 5, 5, 6, 7, 9]

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