加入收藏 | 设为首页 | 会员中心 | 我要投稿 李大同 (https://www.lidatong.com.cn/)- 科技、建站、经验、云计算、5G、大数据,站长网!
当前位置: 首页 > 编程开发 > Python > 正文

python冒泡排序算法的实现代码

发布时间:2020-12-17 08:34:09 所属栏目:Python 来源:网络整理
导读:1.算法描述: (1)共循环 n-1 次 (2)每次循环中,如果 前面的数大于后面的数,就交换 (3)设置一个标签,如果上次没有交换,就说明这个是已经好了的。 2.python冒泡排序代码 复制代码 代码如下: #!/usr/bin/python # -*- coding: utf-8 -*- def bubble(l

1.算法描述:
(1)共循环 n-1 次
(2)每次循环中,如果 前面的数大于后面的数,就交换
(3)设置一个标签,如果上次没有交换,就说明这个是已经好了的。

2.python冒泡排序代码

复制代码 代码如下:

#!/usr/bin/python
# -*- coding: utf-8 -*-

def bubble(l):
    flag = True
    for i in range(len(l)-1,-1):
        if flag:
            flag = False
            for j in range(i):
                if l[j] > l[j + 1]:
                    l[j],l[j+1] = l[j+1],l[j]
                    flag = True
        else:
            break
    print l

li = [21,44,2,45,33,4,3,67]
bubble(li)



结果:[2,21,67]

(编辑:李大同)

【声明】本站内容均来自网络,其相关言论仅代表作者个人观点,不代表本站立场。若无意侵犯到您的权利,请及时与联系站长删除相关内容!

    推荐文章
      热点阅读