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
解决方案
Each time you go through the list, you assume the list is sorted. (1)
Then you iterate the list checking every pair, if the pair is not in the correct order. Swap them. (2)
Because of that incorrect pair: "The whole list must still not be sorted, right?" (assuming again) (3)
Therefore you must repeat until at some point the if-condition is not hit. Then that must mean they are all in correct order. You stop (and print). (4)
def bubble(original_list):
l = original_list.copy() # make a temporary list
sorted = False # Assume list is not sorted at first to kick-start the while loop
count = 0
while not sorted:
sorted = True # (1) Assume that it's sorted
for i in range(0, len(l) - 1): # (2) len(l)-1 because the last element
# has no thing on the right to compare to.
if l[i] > l[i + 1]: # (2) check condition
sorted = False # (3)
count += 1
l[i], l[i + 1] = l[i + 1], l[i] # (2) swap
print("Original: {}".format(original_list)) # (4)
print("Sorted: {}".format(l))
print("Number of swaps: {}".format(count))
Conclusion: Some programming people love assumptions.