python(5) - 冒泡排序

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]
posted @ 2016-03-13 23:07  黄小墨  阅读(408)  评论(0编辑  收藏  举报