【原创】转载请注明作者Johnthegreat和本文链接
冒泡排序在算法中算是最简单也最容易实现的,这里介绍一个非常简单实现的代码:
def bubble_sort(ls): for first in range(len(ls)): for second in range(1, len(ls)): if ls[-first] > ls[-second]: ls[-second], ls[-first] = ls[-first], ls[-second] return ls
以下是运行代码实例:
ls = [46, 12, 35, 34, 6, 346, 4, 6, -5, 45, 4, 5, 4, 5, -45, 3, -45, 345, 34, 5, 345, 34, 5, 34, 53, 4543, -78, 0] result = bubble_sort(ls) print(result)
运行结果如下:
[-78, -45, -45, -5, 0, 3, 4, 4, 4, 5, 5, 5, 5, 6, 6, 12, 34, 34, 34, 34, 35, 45, 46, 53, 345, 345, 346, 4543]
Process finished with exit code 0
相比于其他代码加1或者减1的做法,这个代码干净利落。如有疑问,欢迎评论区留言。