排序算法python版(1)-冒泡排序算法
  TEZNKK3IfmPf 2023年11月14日 29 0

冒泡排序思路:
列表每两个相邻的元素,如果前一个比后一个大,则将这两个数交换
经过第一趟排序最大的数交换到了最后一个
经过第二趟排序第二大的数交换到的倒数第二个

经过n-1趟排序后,整个列表元素即完成了排序
整个过程看上去好像是大的数逐渐向后移动,整个效果看上去就像冒泡一样,因此叫做冒泡法

  • 冒泡算法动态图:

  • 冒泡排序算法的时间复杂度为O(n2

代码如下:

def bubble_sort(datas):
    for i in range(len(datas)-1):
        for j in range(len(datas)-i-1):
            if datas[j]>datas[j+1]:
                datas[j],datas[j+1]=datas[j+1],datas[j]
        print(f"第 {i+1} 轮排序结果:",datas)
    return datas

if __name__=="__main__":
    datas=[10,9,8,7,6,5,4,3,2,1,0]
    datas=bubble_sort(datas)

执行结果如下:

1 轮排序结果: [9, 8, 7, 6, 5, 4, 3, 2, 1, 0, 10]2 轮排序结果: [8, 7, 6, 5, 4, 3, 2, 1, 0, 9, 10]3 轮排序结果: [7, 6, 5, 4, 3, 2, 1, 0, 8, 9, 10]4 轮排序结果: [6, 5, 4, 3, 2, 1, 0, 7, 8, 9, 10]5 轮排序结果: [5, 4, 3, 2, 1, 0, 6, 7, 8, 9, 10]6 轮排序结果: [4, 3, 2, 1, 0, 5, 6, 7, 8, 9, 10]7 轮排序结果: [3, 2, 1, 0, 4, 5, 6, 7, 8, 9, 10]8 轮排序结果: [2, 1, 0, 3, 4, 5, 6, 7, 8, 9, 10]9 轮排序结果: [1, 0, 2, 3, 4, 5, 6, 7, 8, 9, 10]10 轮排序结果: [0, 1, 2, 3, 4, 5, 6, 7, 8, 9, 10]
  • 上述实例展示最坏的情况下,下面测试一下最好情况下:
def bubble_sort(datas):
    for i in range(len(datas)-1):
        for j in range(len(datas)-i-1):
            if datas[j]>datas[j+1]:
                datas[j],datas[j+1]=datas[j+1],datas[j]
        print(f"第 {i+1} 轮排序结果:",datas)
    return datas

if __name__=="__main__":
    datas=[0, 1, 2, 3, 4, 5, 6, 7, 8, 9, 10]
    datas=bubble_sort(datas)

执行结果如下:发现最好的情况下,这里仍然进行了10轮循环

1 轮排序结果: [0, 1, 2, 3, 4, 5, 6, 7, 8, 9, 10]2 轮排序结果: [0, 1, 2, 3, 4, 5, 6, 7, 8, 9, 10]3 轮排序结果: [0, 1, 2, 3, 4, 5, 6, 7, 8, 9, 10]4 轮排序结果: [0, 1, 2, 3, 4, 5, 6, 7, 8, 9, 10]5 轮排序结果: [0, 1, 2, 3, 4, 5, 6, 7, 8, 9, 10]6 轮排序结果: [0, 1, 2, 3, 4, 5, 6, 7, 8, 9, 10]7 轮排序结果: [0, 1, 2, 3, 4, 5, 6, 7, 8, 9, 10]8 轮排序结果: [0, 1, 2, 3, 4, 5, 6, 7, 8, 9, 10]9 轮排序结果: [0, 1, 2, 3, 4, 5, 6, 7, 8, 9, 10]10 轮排序结果: [0, 1, 2, 3, 4, 5, 6, 7, 8, 9, 10]
  • 下面对上述冒泡法做一点优化,即当检测到已经排序之后,停止继续比较
def bubble_sort(datas):
    for i in range(len(datas)-1):
        has_exchange=False
        for j in range(len(datas)-i-1):
            if datas[j]>datas[j+1]:
                has_exchange=True
                datas[j],datas[j+1]=datas[j+1],datas[j]
        print(f"第 {i+1} 轮排序结果:",datas)
        if not has_exchange:
            break
    return datas

if __name__=="__main__":
    datas=[0, 1, 2, 3, 4, 5, 6, 7, 8, 9, 10]
    datas=bubble_sort(datas)

执行结果如下:此时已经做到了在最好的情况下,只需要比较一轮,即比较一轮发现已经排好序了,就停吃继续比较了

1 轮排序结果: [0, 1, 2, 3, 4, 5, 6, 7, 8, 9, 10]
【版权声明】本文内容来自摩杜云社区用户原创、第三方投稿、转载,内容版权归原作者所有。本网站的目的在于传递更多信息,不拥有版权,亦不承担相应法律责任。如果您发现本社区中有涉嫌抄袭的内容,欢迎发送邮件进行举报,并提供相关证据,一经查实,本社区将立刻删除涉嫌侵权内容,举报邮箱: cloudbbs@moduyun.com

  1. 分享:
最后一次编辑于 2023年11月14日 0

暂无评论

推荐阅读
  TEZNKK3IfmPf   2024年05月31日   39   0   0 python开发语言
  TEZNKK3IfmPf   2024年05月31日   28   0   0 python
  TEZNKK3IfmPf   2024年05月31日   35   0   0 excelpython
  TEZNKK3IfmPf   2024年05月31日   31   0   0 python
TEZNKK3IfmPf