def bubble_sort(arr):
n = len(arr)
# 外循环控制每次遍历的次数
for i in range(n):
# 内循环执行实际的比较和交换操作
for j in range(0, n-i-1):
# 比较相邻的元素,如果顺序错误就交换它们
if arr[j] > arr[j+1]:
arr[j], arr[j+1] = arr[j+1], arr[j]
# 打印每一步的排序过程
print(f"Iteration {i+1}, Step {j+1}: {arr}")
return arr
# 示例输入
arr = [64, 34, 25, 12, 22, 11, 90]
# 执行冒泡排序
sorted_arr = bubble_sort(arr.copy())
# 输出排序结果
print("Sorted array:", sorted_a
运行结果:
Iteration 1, Step 1: [34, 64, 25, 12, 22, 11, 90]
Iteration 1, Step 2: [34, 25, 64, 12, 22, 11, 90]
Iteration 1, Step 3: [34, 25, 12, 64, 22, 11, 90]
Iteration 1, Step 4: [34, 25, 12, 22, 64, 11, 90]
Iteration 1, Step 5: [34, 25, 12, 22, 11, 64, 90]
Iteration 2, Step 1: [25, 34, 12, 22, 11, 64, 90]
Iteration 2, Step 2: [25, 12, 34, 22, 11, 64, 90]
Iteration 2, Step 3: [25, 12, 22, 34, 11, 64, 90]
Iteration 2, Step 4: [25, 12, 22, 11, 34, 64, 90]
Iteration 3, Step 1: [12, 25, 22, 11, 34, 64, 90]
Iteration 3, Step 2: [12, 22, 25, 11, 34, 64, 90]
Iteration 3, Step 3: [12, 22, 11, 25, 34, 64, 90]
Iteration 4, Step 1: [12, 22, 11, 25, 34, 64, 90]
Iteration 4, Step 2: [12, 11, 22, 25, 34, 64, 90]
Sorted array: [11, 12, 22, 25, 34, 64, 90]
这个程序首先定义了一个bubble_sort
函数,接受一个待排序的列表作为输入,然后在外循环中控制每次遍历的次数,在内循环中执行实际的比较和交换操作。在每次交换时,程序都会打印出当前的排序状态。最后,程序输出排序完成后的结果。