# 4.冒泡法
# 基础的
lst = [9, 2, 32, 88, 32, 0, 12, 3]
length = len(lst) # 8
for i in range(length): # 0-7
for j in range(length - i - 1):
if lst[j] > lst[j + 1]:
tmp = lst[j]
lst[j] = lst[j + 1]
lst[j + 1] = tmp
print(lst)
# [0, 2, 3, 9, 12, 32, 32, 88]
# 优化的
num_list = [
[1, 9, 8, 5, 6, 7, 4, 3, 2],
[1, 2, 3, 4, 5, 6, 7, 8, 9],
[1, 2, 3, 4, 5, 6, 7, 9, 8]
]
nums = num_list[0]
print(nums)
length = len(nums)
count_swap = 0
count = 0
for i in range(length):
flag = False
for j in range(length - i - 1):
count += 1
if nums[j] > nums[j + 1]:
tmp = nums[j]
nums[j] = nums[j + 1]
nums[j + 1] = tmp
flag = True
count_swap += 1
if not flag:
break
print(nums, count_swap, count)
# [1, 9, 8, 5, 6, 7, 4, 3, 2]
# [1, 2, 3, 4, 5, 6, 7, 8, 9] 25 36
# 使用冒泡算法进行从大到小的顺序排序
num_list = [99, 12, 33, 0, 22, 11, 3, 234, 1]
length = len(num_list)
for i in range(length):
flag = False
for j in range(length - i - 1):
if num_list[j] > num_list[j +1]:
num_list[j], num_list[j+1] = num_list[j + 1], num_list[j]
flag = True
if not flag:
break
print(num_list)
# [0, 1, 3, 11, 12, 22, 33, 99, 234]