【数据结构】冒泡排序-python实现

@【TOC】([数据结构]冒泡排序-python实现)

冒泡排序介绍

冒泡排序通过不断的将较大(较小)的元素进行交换排序(像气泡一样逐渐浮上来),使得原本无序的结果逐渐有序。由于排序时,待选元素会和所有的元素进行对比,所以算法整体是稳定的。

时间复杂度

从无序到最终有序,算法不存在最好或者最坏的情况 (无论结果如何,都会进行遍历)。算法时间复杂度为o(n2)

代码实现

def Bubble(arr = [], comp_func = lambda x, y: x > y):
    ''' generate big sequence
    '''
    # after every loop, arr[i] would be the biggest
    # of arr[0] - arr[i]
    # time complexy is o(n) 
    for i in range(len(arr)-1, 0, -1):
        # use comp_func to find the biggest
        for j in range(i-1):
            # time complexy is o(n) 
            if j > len(arr) or j < 0:
                continue
            if comp_func( arr[j], arr[j+1]):
                # swap
                print("swap %d - %d : %d %d" % (j, j+1, arr[j], arr[j+1]))
                arr[j], arr[j+1] = arr[j+1], arr[j]
    return arr

运行示例

    pre_arr = [0, 1, 2, 4, 1, 6, 2, 6, 9]
    print(Bubble(pre_arr))

在这里插入图片描述

参考推荐 https://www.cnblogs.com/eniac12/p/5329396.html

猜你喜欢

转载自blog.csdn.net/snail010101/article/details/82958115