1 2 3 4

【Python之路22】冒泡排序算法

1、变量互换

a = 123
b = 456

temp = a 
a = b
b = temp 

python比较简单的变量互换:

a = 123
b = 456
a,b = b,a
print(a,b)

 2、将列表中最大的值放置到最后

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

li = [11,44,33,66,22]
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、循环嵌套冒泡排序法

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

li = [11,44,33,66,77,99,44]
for r in range(1,len(li)):
    for i in range(len(li)-r): #1,2,3
        if li[i] > li[i+1]:
            temp = li[i]
            li[i] = li[i+1]
            li[i+1] = temp

print(li)

 

  

posted @ 2017-02-11 09:20  I我的博客I  阅读(295)  评论(0编辑  收藏  举报