码迷,mamicode.com
首页 > 编程语言 > 详细

python 冒泡排序

时间:2016-05-13 18:52:32      阅读:228      评论:0      收藏:0      [点我收藏+]

标签:

冒泡排序:

相邻的两个数字先进行比较,也就是li[0]和li[1]进行比较,如果不是大于的关系,就继续依次进行li[1]和li[2]比较,进行交换然后每一次扫描得到的新列表如下:

#######冒泡排序#######
li = [11,22,32,344,3,]      
for i in range(len(li)-1):      
    xin = (li[i])          
    kai = li[i+1]             
    if li[i] >li[i+1]:
        temp = li[i]
        li[i] = li[i+1]
        li[i+1]=temp
print(li)
for i in range(len(li)-2):
    xin = (li[i])
    kai = li[i+1]
    if li[i] >li[i+1]:
        temp = li[i]
        li[i] = li[i+1]
        li[i+1]=temp
print(li)
for i in range(len(li)-3):
    xin = (li[i])
    kai = li[i+1]
    if li[i] >li[i+1]:
        temp = li[i]
        li[i] = li[i+1]
        li[i+1]=temp
print(li)
for i in range(len(li)-3):
    xin = (li[i])
    kai = li[i+1]
    if li[i] >li[i+1]:
        temp = li[i]
        li[i] = li[i+1]
        li[i+1]=temp
print(li)
执行结果:
[11, 22, 32, 3, 344]
[11, 22, 3, 32, 344]
[11, 3, 22, 32, 344]
[3, 11, 22, 32, 344]

冒泡排序
for j in range(len(li)): #j:1,2,3
    for i in range(len(li)-1):
        if li[i] >li[i+1]:
            temp = li[i]
            li[i] = li[i+1]
            li[i+1]=temp
print(li)

执行结果
[3, 11, 22, 32, 344]

 

python 冒泡排序

标签:

原文地址:http://www.cnblogs.com/guokaixin/p/5490181.html

(0)
(0)
   
举报
评论 一句话评论(0
登录后才能评论!
© 2014 mamicode.com 版权所有  联系我们:gaon5@hotmail.com
迷上了代码!