冒泡排序的过程:从第一个值开始,每取一个值与剩余后面的每个值两两比较,如果后面的值比当前值大,就交换它们的位置
以下是冒泡排序的Python实现:
ls = [2, 5, 3, 11, 7, 9]
for i in range(len(ls)):
for j in range(len(ls) - (i + 1)):
if ls[j + i + 1] > ls[i]:
tmp = ls[j + i + 1]
ls[j + i + 1] = ls[i]
ls[i] = tmp
print(ls) # [11, 9, 7, 5, 3, 2]
# 简化版
for i in range(len(ls)):
for j in range(len(ls) - (i + 1)):
if ls[j + i + 1] > ls[i]:
ls[i], ls[j + i + 1] = ls[j + i + 1], ls[i]
print(ls) # [11, 9, 7, 5, 3, 2]