氣泡排序 (Bubble Sort) 演算法


氣泡排序 (Bubble Sort) 演算法 (algorithm) 又稱為泡沫排序演算法,是在電腦編程中最常用也最基本的排序演算法,是學習程式語言最先需要學會的排序演算法之一。 顧名思義,就是它的排序方式如同氣泡一般,不斷將最大 (或最小) 的元素擠出 (移動) 到陣列最尾端,當所有元素都被擠出後,也就完成了排序。 氣泡排序可用於升序 (從小到大, ascending order) 或降序 (從大到小, descending order),它們在編程的邏輯上實際是相同的。 有關氣泡排序詳細的理論和步驟,請參考 維基百科 (Wikipedia)。
編寫一個程式,將一陣列中的元素(無任何特定順序)重新排列為降序。

# Bubble Sort (descending)

scores = [55, 22, 33, 99, 88, 66, 11, 44, 77]

for n in range(0,len(scores)-1):
   for i in range(0,len(scores)-1-n):
      if (scores[i] < scores[i+1]):
         t = scores[i]
         scores[i] = scores[i+1]
         scores[i+1] = t

print ("Test Scores (from High to Low): ",scores)

執行結果
Test Scores (from High to Low): [99, 88, 77, 66, 55, 44, 33, 22, 11]

如果我們要將 scores 陣列中的元素按升序排列,唯一需要更改的是把
if (scores[i] < scores[i+1]):  改為  if (scores[i] > scores[i+1]):
更改後的完整程式如下

# Bubble Sort (ascending)

scores = [55, 22, 33, 99, 88, 66, 11, 44, 77]

for n in range(0,len(scores)-1):
   for i in range(0,len(scores)-1-n):
      if (scores[i] > scores[i+1]):
         t = scores[i]
         scores[i] = scores[i+1]
         scores[i+1] = t

print ("Test Scores (from High to Low): ",scores)

執行結果
Test Scores (from Low to High): [11, 22, 33, 44, 55, 66, 77, 88, 99]