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

python(5) - 冒泡排序

时间:2016-03-13 23:53:47      阅读:218      评论:0      收藏:0      [点我收藏+]

标签:

data = [10, 4, 33, 21, 54, 3, 8, 11, 5, 22, 2, 1, 17, 13]

‘‘‘
思路:有多少个元素就循环多少次,每次循环从第一个元素开始与它后面的元素比较,如果比后面的大,就交换,第次循环最大的数就会被放在最后,那下一次循环就少遍历一位数。
‘‘‘

for j in range(len(data)-1):
    for i in range(len(data)-1-j):
        if data[i] > data[i+1]:
             data[i], data[i+1] = data[i+1], data[i]
print(data)

把代码修改一下,让它打印出每次循环后的结果

data = [10, 4, 33, 21, 54, 3, 8, 11, 5, 22, 2, 1, 17, 13]

‘‘‘
思路:有多少个元素就循环多少次,从第一个元素开始与它后面的元素比较,如果比后面的大,就交换
‘‘‘

for j in range(len(data)-1):
    for i in range(len(data)-1-j):
        if data[i] > data[i+1]:
             data[i], data[i+1] = data[i+1], data[i]
    print(data)

打印

C:\temp>python3 test.py
[4, 10, 21, 33, 3, 8, 11, 5, 22, 2, 1, 17, 13, 54]
[4, 10, 21, 3, 8, 11, 5, 22, 2, 1, 17, 13, 33, 54]
[4, 10, 3, 8, 11, 5, 21, 2, 1, 17, 13, 22, 33, 54]
[4, 3, 8, 10, 5, 11, 2, 1, 17, 13, 21, 22, 33, 54]
[3, 4, 8, 5, 10, 2, 1, 11, 13, 17, 21, 22, 33, 54]
[3, 4, 5, 8, 2, 1, 10, 11, 13, 17, 21, 22, 33, 54]
[3, 4, 5, 2, 1, 8, 10, 11, 13, 17, 21, 22, 33, 54]
[3, 4, 2, 1, 5, 8, 10, 11, 13, 17, 21, 22, 33, 54]
[3, 2, 1, 4, 5, 8, 10, 11, 13, 17, 21, 22, 33, 54]
[2, 1, 3, 4, 5, 8, 10, 11, 13, 17, 21, 22, 33, 54]
[1, 2, 3, 4, 5, 8, 10, 11, 13, 17, 21, 22, 33, 54]
[1, 2, 3, 4, 5, 8, 10, 11, 13, 17, 21, 22, 33, 54]
[1, 2, 3, 4, 5, 8, 10, 11, 13, 17, 21, 22, 33, 54]

python(5) - 冒泡排序

标签:

原文地址:http://www.cnblogs.com/huangxm/p/5274136.html

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