写个快速排序
- User
写个快速排序
Assistant
这里是一个Python实现的快速排序:
def quick_sort(arr): if len(arr) <= 1: return arr 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) # 使用示例 numbers = [64, 34, 25, 12, 22, 11, 90] sorted_numbers = quick_sort(numbers) print(f"原数组: {numbers}") print(f"排序后: {sorted_numbers}")如果你需要原地排序(不使用额外空间)的版本:
def quick_sort_inplace(arr, low=0, high=None): if high is None: high = len(arr) - 1 if low < high: # 分区操作,返回基准元素的正确位置 pivot_index = partition(arr, low, high) # 递归排序基准左右两部分 quick_sort_inplace(arr, low, pivot_index - 1) quick_sort_inplace(arr, pivot_index + 1, high) def partition(arr, low, high): pivot = arr[high] # 选择最后一个元素作为基准 i = low - 1 # 较小元素的索引 for j in range(low, high): if arr[j] <= pivot: i += 1 arr[i], arr[j] = arr[j], arr[i] # 交换元素 arr[i + 1], arr[high] = arr[high], arr[i + 1] return i + 1 # 使用示例 numbers = [64, 34, 25, 12, 22, 11, 90] print(f"排序前: {numbers}") quick_sort_inplace(numbers) print(f"排序后: {numbers}")
Other models, same or similar prompt
Responses were produced in different, uncontrolled contexts (system prompts, settings, prior turns). This is not a benchmark.