johnthegreat

【原创】转载请注明作者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的做法,这个代码干净利落。如有疑问,欢迎评论区留言。

分类:

技术点:

相关文章:

  • 2020-03-01
  • 2019-11-18
  • 2018-10-13
  • 2019-03-22
  • 2021-03-06
  • 2021-07-27
  • 2018-04-15
猜你喜欢
  • 2019-03-05
  • 2021-01-03
  • 2019-11-29
  • 2021-11-04
  • 2018-01-22
  • 2021-05-23
  • 2018-05-06
相关资源
相似解决方案