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