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

yipeiwu_com6年前Python基础

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, 0, -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, 3, 4, 21, 33, 44, 45, 67]

相关文章

Pycharm导入Python包,模块的图文教程

Pycharm导入Python包,模块的图文教程

1、点击File->settings 2、选择Project Interpreter,点击右边绿色的加号添加包 3、输入你想添加的包名,点击Install Package 4...

Python pyinotify模块实现对文档的实时监控功能方法

0x01 安装pyinotify >>> pip install pyinotify >>> import pyinotify 0x02 实现对...

python 获取utc时间转化为本地时间的方法

方法一: import datetime timenow = (datetime.datetime.utcnow() + datetime.timedelta(hours=8))...

python随机取list中的元素方法

python随机取list中的元素方法

随机取 list 中的元素 random.sample import random a = [1, 2, 3, 4, 5, 6, 7, 8, 9] b = random.sample...

树莓派使用python-librtmp实现rtmp推流h264的方法

目的是能使用Python进行rtmp推流,方便在h264帧里加入弹幕等操作。 librtmp使用的是0.3.0,使用树莓派noir官方摄像头适配的。 通过wireshark抓ffmpeg...