from random import randint
def bubbleSort(lst, reverse=False):
length = len(lst)
for i in range(0, length):
for j in range(0, length-i-1):
#比较相邻两个元素大小,并根据需要进行交换
#默认升序排序
exp = 'lst[j] > lst[j+1]'
#如果reverse=True则降序排序
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)