Files
demo-workflow-repo/quicksort.py
2025-10-20 13:11:09 +00:00

15 lines
470 B
Python
Raw Blame History

This file contains ambiguous Unicode characters
This file contains Unicode characters that might be confused with other characters. If you think that this is intentional, you can safely ignore this warning. Use the Escape button to reveal them.
def quick_sort(arr):
if len(arr) <= 1:
return arr # 递归终止条件数组长度为1或为空
pivot = arr[len(arr) // 2] # 选取中间元素作为基准
left = [x for x in arr if x < pivot]
middle = [x for x in arr if x == pivot]
right = [x for x in arr if x > pivot]
return quick_sort(left) + middle + quick_sort(right)
# 示例
nums = [3, 6, 8, 10, 1, 2, 1]
print("排序前:", nums)
print("排序后:", quick_sort(nums))