[英]Bubble Sort in Python 3
用 Python 3 編寫冒泡排序程序。 冒泡排序是一種將值列表按順序排序的算法。
我試圖在最后得到這個結果。
Original List: 4, 9, 74, 0, 9, 8, 28, 1
Sorted List: 0, 1, 4, 8, 9, 9, 28, 74
Number of Passes: 6
我怎樣才能完成它?
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)
我得到的輸出:
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
我想要的結果:
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
關於文本格式 - 將','
替換為','
', '
(添加一個空格)。
關於 Pass 0 的打印(甚至在您運行之前) - 將打印調用移動到passes += 1
最后 - 在您的示例中通過冒泡排序完成的傳遞次數將為 7 - 6 次傳遞,您仍然修改列表,最后一次傳遞檢測到列表已排序。
修改后的代碼如下:
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)
首先,它確實需要 7,因為最后一次傳遞沒有交換(那是它知道它完成的時候)。 將passes += 1
和 print 語句移動到循環的末尾將正確顯示這一點。
對於您想要的輸出,更改循環中事件的順序並添加 if 語句以檢查更改。 [下面給出]
對於實際傳遞的輸出(包括最后一個沒有變化的傳遞),只需從下面的代碼中刪除 if 語句。
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)
這就是解決方案:
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)
為了不再對已經排序的列表進行排序並且不向傳遞添加 +1,您必須添加以下行:
if swapped: passes += 1 print('Pass', passes, ':' , ','.join(map(str, mylist)))
接下來,如果您不想在第一次通過循環后獲得原始字母,則在所有操作之后將顯示列表的行放在循環中。
這是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]
我相信這是最有效(也最容易理解)的冒泡排序方法:
def bubbleSort(arr):
n = len(arr)
for i in range(n): # i : 1 -> n
for j in range(0, n - i - 1): # j -> n -i -1 , -1 for the j+1 comparison of last element
if arr[j] > arr[j + 1]: # if current is bigger than next
arr[j], arr[j + 1] = arr[j + 1], arr[j] # swap current and next
return arr
使用下面的代碼並重復列表中的數字。
theList = [18, 9, 6, 10]
currentNumber = theList[0]
nextNumber = theList[1]
`if` nextNumber < currentNumber:
toSwap = theList[0]
theList[0] = theList[1]
theList[1
] = toSwap
currentNumber = theList[1]
nextNumber = theList[2]
def bubblesort(lis):
num_of_iterations = 0
for i in range(len(lis)):
for j in range(i):
if lis[j]>lis[j+1]:
lis[j], lis[j+1] = lis[j+1], lis[j]
num_of_iterations += 1
print(lis,"\n num_of_iterations : ",num_of_iterations)
y =[19,2,31,45,6,11,121,27]
bubblesort(y)
每次瀏覽列表時,您都假定列表已排序。 (1)
然后迭代列表檢查每一對,如果對的順序不正確。 交換它們。 (2)
因為那個不正確的對:“整個列表一定還沒有排序,對吧?” (再次假設)(3)
因此,您必須重復,直到在某個時候沒有滿足 if 條件。 那么這一定意味着它們都按正確的順序排列。 您停止(並打印)。 (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))
結論:一些編程人員喜歡假設。
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.