Bubble Sort in Python 3

2019-08-29 01:55发布

问题:

Write a bubble sort program in Python 3. A bubble sort is an algorithm that will sort a list of values into order.

I am trying to get this result towards the end.

Original List: 4, 9, 74, 0, 9, 8, 28, 1
Sorted List: 0, 1, 4, 8, 9, 9, 28, 74
Number of Passes: 6

How can I accomplish it?

import sys
def bubblesort(mylist):
        changes = passes = 0
        last = len(mylist)
        swapped = True
        print("Original List: ", ','.join(map(str, mylist)) )
        while swapped:
                swapped = False
                for j in range(1, last):
                        if mylist[j - 1] > mylist[j]:
                                mylist[j], mylist[j - 1] = mylist[j - 1], mylist[j]  # Swap
                                changes += 1
                                swapped = True
                                last = j
                if swapped:
                        passes += 1
                        print('Pass', passes, ':' , ','.join(map(str, mylist)))

        print("\nOriginal List: ", ','.join(map(str, mylist)) )
        print("Sorted List: ", ','.join(map(str, mylist)))
        print("Number of passes =",passes)
        return mylist

print("Welcome to a Bubble Sort Algorithm in Python!")
mylist = " "
while True:
    print("\nBubble sort in Python 3 Program")
    mylist = input("Enter a the value or type Exit to exit: ")
    if (mylist == "exit" or mylist == "Exit" or mylist == "EXIT"):
        print("Goodbye")
        sys.exit()
    else:
        mylist = [int(v) for v in mylist.split(',')]
        bubblesort(mylist)

The output that I get:

Original List:  4,9,74,0,9,8,28,1
Pass 0 : 4,9,74,0,9,8,28,1
Pass 1 : 4,9,0,9,8,28,1,74
Pass 2 : 4,0,9,8,9,1,28,74
Pass 3 : 0,4,8,9,1,9,28,74
Pass 4 : 0,4,8,1,9,9,28,74
Pass 5 : 0,4,1,8,9,9,28,74
Pass 6 : 0,1,4,8,9,9,28,74


Original List: 0, 1, 4, 8, 9, 9, 28, 74
Sorted List: 0, 1, 4, 8, 9, 9, 28, 74
Number of Passes: 6

The result that I want:

Original List: 4, 9, 74, 0, 9, 8, 28, 1
Pass 1:  4, 9, 0, 9, 8, 28, 1, 74
Pass 2:  4, 0, 9, 8, 9, 1, 28, 74
Pass 3 : 0, 4, 8, 9, 1, 9, 28, 74
Pass 4 : 0, 4, 8, 1, 9, 9, 28, 74
Pass 5 : 0, 4, 1, 8, 9, 9, 28, 74
Pass 6 : 0, 1, 4, 8, 9, 9, 28, 74

Original List: 4, 9, 74, 0, 9, 8, 28, 1
Sorted List: 0, 1, 4, 8, 9, 9, 28, 74
Number of Passes: 6

回答1:

Regarding text formatting - replace the ',' with ', ' (add a space).

Regarding printing of Pass 0 (which is before you even run) - move the print invocation to be after passes += 1

And finally - the number of passes done by bubble sort in your example would be 7 - 6 passes in which you still modify the list, and a final pass in which you detect the list is sorted.

The modified code would look be:

import sys
def bubblesort(mylist):
    changes = passes = 0
    last = len(mylist)
    swapped = True
    print("Original List: ", ', '.join(map(str, mylist)) )
    while swapped:
        swapped = False
        for j in range(1, last):
            if mylist[j - 1] > mylist[j]:
                mylist[j], mylist[j - 1] = mylist[j - 1], mylist[j]  # Swap
                changes += 1
                swapped = True
                last = j
        passes += 1
        print('Pass', passes, ':', ', '.join(map(str, mylist)))

    print("Number of passes =",passes)
    return mylist

print("Welcome to a Bubble Sort Algorithm in Python!")

while True:
    print("\nBubble sort in Python 3 Program")
    mylist = input("Enter a the value or type Exit to exit: ")
    if (mylist == "exit" or mylist == "Exit" or mylist == "EXIT"):
        print("Goodbye")
        sys.exit()
    else:
        mylist = [int(v) for v in mylist.split(',')]
        bubblesort(mylist)


回答2:

That's the solution:


    import sys
    def bubblesort(mylist):
        changes = passes = 0
        last = len(mylist)
        swapped = True
        print("Original List: ", ','.join(map(str, mylist)) )
        while swapped:
            swapped = False
            for j in range(1, last):
                if mylist[j - 1] > mylist[j]:
                    mylist[j], mylist[j - 1] = mylist[j - 1], mylist[j]  # Swap
                    changes += 1
                    swapped = True
                    last = j
            if swapped:
                passes += 1
                print('Pass', passes, ':' , ','.join(map(str, mylist)))

        print("Number of passes =",passes)
        return mylist

    print("Welcome to a Bubble Sort Algorithm in Python!")

    mylist = " "
    while True:
        print("\nBubble sort in Python 3 Program")
        mylist = input("Enter a the value or type Exit to exit: ")
        if (mylist == "exit" or mylist == "Exit" or mylist == "EXIT"):
            print("Goodbye")
            sys.exit()
        else:
            mylist = [int(v) for v in mylist.split(',')]
            bubblesort(mylist)

In order to not to sort already sorted list again and not to add +1 to passes you have to add this line:


    if swapped:
            passes += 1
            print('Pass', passes, ':' , ','.join(map(str, mylist)))

Next, put the line where you display a list in loop AFTER all actions with it if you don't want to get original letter after the first pass through loop.



回答3:

First, it does take 7 because the last pass has no swaps (that's when it knows its done). Moving the passes += 1 and the print statement to the end of the loop will show this correctly.

For the output you want, change around the order of events in your loop and add an if statement to check for changes. [ Given Below ]

For the output of the actual passes (including the last one where there is no change) just remove the if statement from the code below.

import sys

def bubblesort(mylist):
    changes = passes = 0
    last = len(mylist)
    swapped = True
    print("Original List: ", ','.join(map(str, mylist)) )
    while swapped:
        swapped = False

        for j in range(1, last):
            if mylist[j - 1] > mylist[j]:
                mylist[j], mylist[j - 1] = mylist[j - 1], mylist[j]  # Swap
                changes += 1
                swapped = True
                last = j

        # Only prints and increases number of passes if there was a swap
        # Remove if statement for the correct number of passes
        if(swapped):
          passes += 1
          print('Pass', passes, ':' , ','.join(map(str, mylist)))

    print("Number of passes =",passes)
    return mylist

print("Welcome to a Bubble Sort Algorithm in Python!")

mylist = " "
while True:
    print("\nBubble sort in Python 3 Program")
    mylist = input("Enter a the value or type Exit to exit: ")
    if (mylist == "exit" or mylist == "Exit" or mylist == "EXIT"):
        print("Goodbye")
        sys.exit()
    else:
        mylist = [int(v) for v in mylist.split(',')]
        bubblesort(mylist)


回答4:

This is a simple application of bubble sort in python

l=[1,6,3,7,5,9,8,2,4,10]

for i in range(1,len(l)):
    for j in range (i+1,len(l)):
        if l[i]>l[j]:
            l[i],l[j]=l[j],l[i]