数据结构算法-冒泡排序

冒泡排序:

  1. 冒泡排序,每次都是从左往右,交换相邻的元素,从而达到循环一边可以把最大的元素放在右边。
  2. 时间复杂度:平均:O(n²),最好:O(n),最坏:O(n2),稳定性:稳定。

  上代码

def bubble(lists, map=lambda x, y: x>y):
    # 未优化
    # 冒泡排序。
    # listlen = len(lists)
    for x in range(len(lists)-1):
        istrue = False
        for i in range(len(lists)-1):
            if map(lists[i], lists[i+1]):
                istrue=True
                lists[i], lists[i+1] = lists[i+1], lists[i]
        if not istrue:
            break

    return lists

lists = [54, 26, 93, 77,17, 77, 31, 44, 55, 20]
print(bubbling(lists))

双向冒泡排序

从名字就可以看出来,是双向的冒泡排序。
冒泡排序,每次都是从左往右,交换相邻的元素,从而达到循环一边可以把最大的元素放在右边。
而双向冒泡排序,在完成一次从左往右的冒泡排序后,再从右往左进行冒泡,从而把小的元素放在左边。

 

上图

在这里插入图片描述

上码

def bubbling(lists, map=lambda x, y: x>y):
    # 双向冒泡排序。
    for x in range(len(lists)-1):
        istrue = False
        for i in range(len(lists)-1):
            if map(lists[i], lists[i+1]):
                lists[i], lists[i+1] = lists[i+1], lists[i]
                istrue = True

        if istrue == True:
            for i in range(len(lists)-2, x, -1):
                if map(lists[i-1], lists[i]):

                    lists[i-1], lists[i] = lists[i], lists[i-1]
                    istrue = True
        if not istrue:
            break
    return lists

lists = [8, 7, 6, 5, 4, 3, 2, 1]
print(bubbling(lists))

 

  • 0
    点赞
  • 1
    收藏
    觉得还不错? 一键收藏
  • 0
    评论

“相关推荐”对你有帮助么?

  • 非常没帮助
  • 没帮助
  • 一般
  • 有帮助
  • 非常有帮助
提交
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值