python - 冒泡排序
Posted 黄小墨
tags:
篇首语:本文由小常识网(cha138.com)小编为大家整理,主要介绍了python - 冒泡排序相关的知识,希望对你有一定的参考价值。
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 - 冒泡排序的主要内容,如果未能解决你的问题,请参考以下文章