本文摘自php中文网,作者藏色散人,侵删。
冒泡排序是一种简单的排序技术,它通过比较相邻的元素遍历整个列表,对它们进行排序并交换元素,直到对整个列表进行排序。
算法:给定一个包含n个元素的列表L,这些元素的值或记录为L0, L1,…,Ln-1,冒泡排序用于对列表L进行排序。
比较列表中的前两个元素L0和L1。
如果L1 < L0,交换这些元素,然后继续下面的两个元素。
重复相同的步骤,直到整个列表被排序,这样就不可能进行更多的交换。
返回最终排序的列表。
python冒泡排序代码如下:
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 | __author__ = 'Avinash'
def bubble_sort(sort_list):
for j in range(len(sort_list)):
for k in range(len(sort_list) - 1):
if sort_list[k] > sort_list[k + 1]:
sort_list[k], sort_list[k + 1] = sort_list[k + 1], sort_list[k]
print (sort_list)
lst = []
size = int(input( "Enter size of the list: \t" ))
for i in range(size):
elements = int(input( "Enter the element: \t" ))
lst.append(elements)
bubble_sort(lst)
|
输出:


相关推荐:《Python教程》
本篇文章就是关于python冒泡排序算法的方法介绍,希望对需要的朋友有所帮助!
以上就是如何实现python冒泡排序算法?的详细内容,更多文章请关注木庄网络博客!!
相关阅读 >>
go语言和Python哪个难
Python如何编写安卓程序
django 在Python3.5 下报 没有模块mysqldb的解决方法
类的实例化介绍
Python字符串截取如何操作
Python怎么调用api接口
Python里len什么意思
总结2020年最强Python库
Python pop函数的定义及使用方式(实例展示)
Python单引号怎么打
更多相关阅读请进入《Python》频道 >>
人民邮电出版社
python入门书籍,非常畅销,超高好评,python官方公认好书。
转载请注明出处:木庄网络博客 » 如何实现python冒泡排序算法?