编程解决问题:输入一组数据,以0作为输入的结束,分别采用冒泡排序、选择排序、快速排序的方法,对其进行从小到大的排序,给出排序后的结果
时间: 2024-02-17 21:03:19 浏览: 14
好的,这里是 Python 代码,可以实现对输入数据进行冒泡排序、选择排序和快速排序的功能,最后输出排序后的结果:
```python
def bubble_sort(arr):
n = len(arr)
for i in range(n):
for j in range(n-i-1):
if arr[j] > arr[j+1]:
arr[j], arr[j+1] = arr[j+1], arr[j]
return arr
def selection_sort(arr):
n = len(arr)
for i in range(n):
min_idx = i
for j in range(i+1, n):
if arr[j] < arr[min_idx]:
min_idx = j
arr[i], arr[min_idx] = arr[min_idx], arr[i]
return arr
def quick_sort(arr):
if len(arr) <= 1:
return arr
else:
pivot = arr[0]
left = [x for x in arr[1:] if x < pivot]
right = [x for x in arr[1:] if x >= pivot]
return quick_sort(left) + [pivot] + quick_sort(right)
# 输入数据
arr = []
while True:
x = int(input("请输入一个数字(以0结束):"))
if x == 0:
break
arr.append(x)
# 对数据进行排序
sorted_arr_bubble = bubble_sort(arr.copy())
sorted_arr_selection = selection_sort(arr.copy())
sorted_arr_quick = quick_sort(arr.copy())
# 输出排序后的结果
print("冒泡排序的结果为:", sorted_arr_bubble)
print("选择排序的结果为:", sorted_arr_selection)
print("快速排序的结果为:", sorted_arr_quick)
```
代码中,`bubble_sort`、`selection_sort`、`quick_sort` 分别实现了冒泡排序、选择排序和快速排序算法。在主程序中,通过循环读入输入数据,当读到 0 时跳出循环,把输入的数字保存在列表 `arr` 中。然后分别对 `arr` 进行三种排序算法,得到排序后的结果。最后,使用 `print` 函数输出排序后的结果。
希望这段代码能对你有所帮助!
相关推荐
![doc](https://img-home.csdnimg.cn/images/20210720083327.png)
![zip](https://img-home.csdnimg.cn/images/20210720083736.png)
![zip](https://img-home.csdnimg.cn/images/20210720083736.png)
![-](https://csdnimg.cn/download_wenku/file_type_column_c1.png)
![](https://csdnimg.cn/download_wenku/file_type_ask_c1.png)
![](https://csdnimg.cn/download_wenku/file_type_ask_c1.png)
![](https://csdnimg.cn/download_wenku/file_type_ask_c1.png)
![](https://csdnimg.cn/download_wenku/file_type_ask_c1.png)
![](https://csdnimg.cn/download_wenku/file_type_ask_c1.png)
![](https://csdnimg.cn/download_wenku/file_type_ask_c1.png)
![](https://csdnimg.cn/download_wenku/file_type_ask_c1.png)
![](https://csdnimg.cn/download_wenku/file_type_ask_c1.png)
![](https://csdnimg.cn/download_wenku/file_type_ask_c1.png)
![](https://csdnimg.cn/download_wenku/file_type_ask_c1.png)
![](https://csdnimg.cn/download_wenku/file_type_ask_c1.png)
![](https://csdnimg.cn/download_wenku/file_type_ask_c1.png)
![](https://csdnimg.cn/download_wenku/file_type_ask_c1.png)
![](https://csdnimg.cn/download_wenku/file_type_ask_c1.png)