算法——冒泡排序

参考: 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

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