算法——冒泡排序

參考: http://bubkoo.com/2014/01/12/sort-algorithm/bubble-sort/

算法原理:

冒泡排序(Bubble Sort,臺灣譯爲:泡沫排序或氣泡排序)是一種簡單的排序算法。

重複地走訪過要排序的數列,一次比較兩個元素,如果他們的順序錯誤,則把他們交換過來(順序可自行設定,通常期待前者小於後者)。

走訪數列的工作,是重複地進行直到沒有再需要交換,也就是說該數列已經排序完成。
這個算法的名字由來是因爲越小的元素會經由交換慢慢“浮”到數列的頂端。

算法流程如下:

1.比較相鄰的元素,如果第一個比第二個大,就交換他們兩個。
2.對每一對相鄰元素作同樣的工作,從開始第一對到結尾的最後一對。在這一點,最後的元素應該會是最大的數。
3.針對所有的元素重複以上的步驟,除了最後一個。
4.持續每次對越來越少的元素重複上面的步驟,直到沒有任何一對數字需要比較。



實例分析

以數組 arr = [5, 1, 4, 2, 8] 爲例說明,加粗的數字表示每次循環要比較的兩個數字:

第一次外循環

( 5 1 4 2 8 ) → ( 1 5 4 2 8 ), 5 > 1 交換位置
( 1 5 4 2 8 ) → ( 1 4 5 2 8 ), 5 > 4 交換位置
( 1 4 5 2 8 ) → ( 1 4 2 5 8 ), 5 > 2 交換位置
( 1 4 2 5 8 ) → ( 1 4 2 5 8 ), 5 < 8 位置不變

第二次外循環(除開最後一個元素8,對剩餘的序列)

( 1 4 2 5 8 ) → ( 1 4 2 5 8 ), 1 < 4 位置不變
( 1 4 2 5 8 ) → ( 1 2 4 5 8 ), 4 > 2 交換位置
( 1 2 4 5 8 ) → ( 1 2 4 5 8 ), 4 < 5 位置不變

第三次外循環(除開已經排序好的最後兩個元素,可以注意到上面的數組其實已經排序完成,但是程序本身並不知道,所以還要進行後續的循環,直到剩餘的序列爲 1)

( 1 2 4 5 8 ) → ( 1 2 4 5 8 )
( 1 2 4 5 8 ) → ( 1 2 4 5 8 )

第四次外循環(最後一次)
( 1 2 4 5 8 ) → ( 1 2 4 5 8 )



代碼實現 (move larger to the right)

Normal method is that in each pair comparision step, we move the bigger one to the right,
and finally we can move the largest one to the right end at the ending of this comparison cycle.

def bubble_sort(L):
    if L:
        n = len(L)

        while n > 1:
            for i in range(n-1):
                if L[i] > L[i+1]:
                    L[i], L[i+1] = L[i+1], L[i]
            n -= 1
        return L

    else:
        return None


代碼實現(move smaller to the left)

Or, we can move the smaller one to the left during each pair comparison,
and finally we can move the smallest one to the left end at the ending of this comparision cycle.

def bubble_sort(array):

    if array:

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

        print(array)

This implementation is a bit similar to Selection Sort

發表評論
所有評論
還沒有人評論,想成為第一個評論的人麼? 請在上方評論欄輸入並且點擊發布.
相關文章