按快速排序原理实现排序。要求运行后控制台输入待排序数据,并显示快速排序过程中第一趟划分结果以及排序结果。请用完整的python代码输出
时间: 2024-10-13 12:08:23 浏览: 26
可以使用Python编写快速排序算法来实现这个功能。以下是完整的代码示例:
```python
def quicksort(arr):
if len(arr) <= 1:
return arr
pivot = arr[len(arr) // 2]
less = [x for x in arr if x < pivot]
equal = [x for x in arr if x == pivot]
greater = [x for x in arr if x > pivot]
return quicksort(less) + equal + quicksort(greater)
def display_partition_result(arr, index=0, end=None):
if end is None:
end = len(arr)
first_split = arr[index:end]
print(f"First partition after {index}th pass: {first_split}")
print(f"Sorted array after {index}th pass: {quicksort(arr)}")
# 获取用户输入
unsorted_data = input("Enter a list of numbers separated by spaces to sort (or press enter to use the example: ")
if unsorted_data == "":
data = [3,6,8,10,1,2,1]
else:
data = list(map(int, unsorted_data.split()))
display_partition_result(data)
quicksorted_data = quicksort(data)
print(f"Final sorted array: {quicksorted_data}")
阅读全文