简体   繁体   中英

Python bubble sort - Sorting an element more than once

The objective of this is to take a list of positive integers and sort them using bubble sort. It works whenever you input a list that does not require a single element to be moved more than once. How do I get it to move an element more than once?

For example, inputting [3,5,4,6,7] works but [10,9,8,7,6] does not.

def bubbleSort(lis):    
        swapped = True
        while swapped:
                swapped = False
                for i in range(0,len(lis)-1):
                        if lis[i] > lis[i + 1] or lis[i] == lis[i+1]:
                            switch = lis[i]
                            lis[i] = lis[i+1]
                            lis[i+1] = switch
                return lis
                print(lis)


print(bubbleSort([3,5,4,6,7]))
print(bubbleSort([10,9,8,7,6]))

The problem is that you return after only one pass through the list. Wait until swapped is False .

Also, you must set swapped when you make a switch.

    swapped = True
    while swapped:
            swapped = False
            for i in range(0,len(lis)-1):
                    if lis[i] > lis[i + 1] or lis[i] == lis[i+1]:
                        swapped = True
                        switch = lis[i]
                        lis[i] = lis[i+1]
                        lis[i+1] = switch
    return lis

I removed the print statement because you can never reach it, and that should be the job of the calling program.

You should not set swapped to 'false' when you enter the while loop, because then you make only one iteration of the loop. You should exit the loop when there are no more swaps when you iterate over the entire list.

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