python---冒泡和短冒泡排序

冒泡是最费时的排序,但可以自定义更多步骤。

短冒泡确实可以加快性能。

# coding = utf-8


# ========冒泡排序========
def bubble_sort(a_list):
    loop_count = 0
    swap_count = 0
    for i in range(len(a_list)):
        loop_count += 1
        for j in range(i+1, len(a_list)):
            # print(a_list)
            loop_count += 1
            if a_list[i] > a_list[j]:
                swap_count += 1
                a_list[i], a_list[j] = a_list[j], a_list[i]
    print('======== bubble_sort loop_count========', loop_count)
    print('========bubble_sort swap_count========', swap_count)


# '========短冒泡排序========
def short_bubble_sort(a_list):
    loop_count = 0
    swap_count = 0
    exchange = True
    pass_num = len(a_list) - 1
    while pass_num > 0 and exchange:
        loop_count += 1
        exchange = False
        for i in range(pass_num):
            loop_count += 1
            if a_list[i] > a_list[i+1]:
                swap_count += 1
                exchange = True
                temp = a_list[i]
                a_list[i] = a_list[i + 1]
                a_list[i + 1] = temp
        pass_num -= 1
    print('========short_bubble_sort loop_count========', loop_count)
    print('========short_bubble_sort swap_count========', swap_count)


my_list = [4, 5, 7, 2, 9, 7, 9, 54, 765, 45, 9876, 34, 12343, 36]
bubble_sort(my_list)
print(my_list)

my_short_list = [4, 5, 7, 2, 9, 7, 9, 54, 765, 45, 9876, 34, 12343, 36]
short_bubble_sort(my_short_list)
print(my_short_list)

  

D:\cheng\test\Scripts\python.exe D:/GIT/Prism4K/Prism4K/document/tests.py
======== bubble_sort loop_count======== 105
========bubble_sort swap_count======== 15
[2, 4, 5, 7, 7, 9, 9, 34, 36, 45, 54, 765, 9876, 12343]
========short_bubble_sort loop_count======== 69
========short_bubble_sort swap_count======== 15
[2, 4, 5, 7, 7, 9, 9, 34, 36, 45, 54, 765, 9876, 12343]

Process finished with exit code 0

  

转载于:https://www.cnblogs.com/aguncn/p/10683723.html

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

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值