1. 设计冒泡排序算法,输出每一趟的排序结果。并用相关数据进行测试。
时间: 2023-07-15 17:10:25 浏览: 46
冒泡排序算法的基本思想是对待排序的元素进行两两比较,如果发现逆序则交换位置,直到没有逆序的元素为止。下面是冒泡排序算法的实现代码:
```python
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"第{i+1}趟排序结果:{arr}")
return arr
```
该算法的时间复杂度是$O(n^2)$,其中$n$是待排序元素的个数。
下面是使用该算法对一些数据进行排序的示例:
```python
arr1 = [5, 2, 8, 4, 9, 1, 6, 3, 7]
print("原始数据:", arr1)
bubble_sort(arr1)
print("排序结果:", arr1)
arr2 = [1, 2, 3, 4, 5, 6, 7, 8, 9]
print("原始数据:", arr2)
bubble_sort(arr2)
print("排序结果:", arr2)
arr3 = [9, 8, 7, 6, 5, 4, 3, 2, 1]
print("原始数据:", arr3)
bubble_sort(arr3)
print("排序结果:", arr3)
```
输出结果如下:
```
原始数据: [5, 2, 8, 4, 9, 1, 6, 3, 7]
第1趟排序结果:[2, 5, 4, 8, 1, 6, 3, 7, 9]
第2趟排序结果:[2, 4, 5, 1, 6, 3, 7, 8, 9]
第3趟排序结果:[2, 4, 1, 5, 3, 6, 7, 8, 9]
第4趟排序结果:[2, 1, 4, 3, 5, 6, 7, 8, 9]
第5趟排序结果:[1, 2, 3, 4, 5, 6, 7, 8, 9]
第6趟排序结果:[1, 2, 3, 4, 5, 6, 7, 8, 9]
第7趟排序结果:[1, 2, 3, 4, 5, 6, 7, 8, 9]
第8趟排序结果:[1, 2, 3, 4, 5, 6, 7, 8, 9]
第9趟排序结果:[1, 2, 3, 4, 5, 6, 7, 8, 9]
排序结果: [1, 2, 3, 4, 5, 6, 7, 8, 9]
原始数据: [1, 2, 3, 4, 5, 6, 7, 8, 9]
第1趟排序结果:[1, 2, 3, 4, 5, 6, 7, 8, 9]
第2趟排序结果:[1, 2, 3, 4, 5, 6, 7, 8, 9]
第3趟排序结果:[1, 2, 3, 4, 5, 6, 7, 8, 9]
第4趟排序结果:[1, 2, 3, 4, 5, 6, 7, 8, 9]
第5趟排序结果:[1, 2, 3, 4, 5, 6, 7, 8, 9]
第6趟排序结果:[1, 2, 3, 4, 5, 6, 7, 8, 9]
第7趟排序结果:[1, 2, 3, 4, 5, 6, 7, 8, 9]
第8趟排序结果:[1, 2, 3, 4, 5, 6, 7, 8, 9]
第9趟排序结果:[1, 2, 3, 4, 5, 6, 7, 8, 9]
排序结果: [1, 2, 3, 4, 5, 6, 7, 8, 9]
原始数据: [9, 8, 7, 6, 5, 4, 3, 2, 1]
第1趟排序结果:[8, 7, 6, 5, 4, 3, 2, 1, 9]
第2趟排序结果:[7, 6, 5, 4, 3, 2, 1, 8, 9]
第3趟排序结果:[6, 5, 4, 3, 2, 1, 7, 8, 9]
第4趟排序结果:[5, 4, 3, 2, 1, 6, 7, 8, 9]
第5趟排序结果:[4, 3, 2, 1, 5, 6, 7, 8, 9]
第6趟排序结果:[3, 2, 1, 4, 5, 6, 7, 8, 9]
第7趟排序结果:[2, 1, 3, 4, 5, 6, 7, 8, 9]
第8趟排序结果:[1, 2, 3, 4, 5, 6, 7, 8, 9]
第9趟排序结果:[1, 2, 3, 4, 5, 6, 7, 8, 9]
排序结果: [1, 2, 3, 4, 5, 6, 7, 8, 9]
```
相关推荐
![text/plain](https://img-home.csdnimg.cn/images/20210720083646.png)
![application/msword](https://img-home.csdnimg.cn/images/20210720083327.png)
![pdf](https://img-home.csdnimg.cn/images/20210720083512.png)
![zip](https://img-home.csdnimg.cn/images/20210720083736.png)
![rar](https://img-home.csdnimg.cn/images/20210720083606.png)
![docx](https://img-home.csdnimg.cn/images/20210720083331.png)
![pdf](https://img-home.csdnimg.cn/images/20210720083512.png)
![zip](https://img-home.csdnimg.cn/images/20210720083736.png)
![zip](https://img-home.csdnimg.cn/images/20210720083736.png)
![zip](https://img-home.csdnimg.cn/images/20210720083736.png)
![rar](https://img-home.csdnimg.cn/images/20210720083606.png)