from random
import randint
'''
该方法传入两个参数
lst:当前待排序列表
reserve 若不传值,默认为True
reserve = True 从大到小排列
reserve = False 从小到大排列
'''
def bubbleSort(lst, reverse=True):
length = len(lst)
for i
in range(
0, length):
for j
in range(
0, length - i -
1):
exp =
'lst[j] > lst[j+1]'
if reverse:
exp =
'lst[j] < lst[j+1]'
if eval(exp):
lst[j], lst[j +
1] = lst[j +
1], lst[j]
lst = [randint(
1,
100)
for i
in range(
20)]
print(
'Before sort:\n', lst)
bubbleSort(lst,
True)
print(
'After sort:\n', lst)
运行结果
转载于:https://www.cnblogs.com/bilaisheng/p/10211030.html
相关资源:基于Python的冒泡排序代码