1 Algorithm description
Compare adjacent elements, and if the former is larger than the latter, swap them.
The first pass sorts the 1st and 2nd pair, compares and swaps, then compares and swaps the 2nd and 3rd pair, so that until the penultimate 2nd and last 1, move the largest number to the last bit.
The second pass moves the second largest number to the penultimate place
...
so it takes n-1 passes;
2 code implementation
def bobble_sort(li):
# 外层循环
for i in range(len(li) - 1):
# print(li)
for j in range(len(li) - i - 1):
# 两相邻元素比较
if li[j] > li[j + 1]:
# 如果前面的元素大于后面的元素 就进行数据替换
li[j], li[j + 1] = li[j + 1], li[j]
test code
li = [3, 2, 4, 7, 1, 2]
# 排序前
print(li)
# 执行排序
bobble_sort(li)
# 排序后
print(li)
dynamic