Home > Backend Development > Python Tutorial > python冒泡排序算法的实现代码

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

WBOY
Release: 2016-06-16 08:46:13
Original
1486 people have browsed it

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]
Related labels:
source:php.cn
Statement of this Website
The content of this article is voluntarily contributed by netizens, and the copyright belongs to the original author. This site does not assume corresponding legal responsibility. If you find any content suspected of plagiarism or infringement, please contact admin@php.cn
Popular Tutorials
More>
Latest Downloads
More>
Web Effects
Website Source Code
Website Materials
Front End Template