快速排序代码实现详解
快速排序代码实现详解
快速排序(Quick Sort)是一种高效的分治算法,平均时间复杂度为 O(n log n)。其核心思想是选择一个基准元素(pivot),将数组划分为两部分:小于基准的部分和大于基准的部分,然后递归地对这两部分排序。
快速排序步骤:
-  选择基准:从数组中选择一个元素作为基准(pivot)。 
-  分区操作:重新排列数组,所有小于基准的元素放在基准左侧,大于基准的元素放在右侧。 
-  递归排序:对左右子数组递归执行上述步骤。 
Python 代码实现
def quick_sort(arr):if len(arr) <= 1:return arrpivot = 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)# 测试
arr = [3, 6, 8, 10, 1, 2, 1]
sorted_arr = quick_sort(arr)
print("Sorted array:", sorted_arr)原地分区版本(优化空间复杂度)
上述实现需要额外空间。以下是原地分区的优化版本(空间复杂度 O(log n)):
def quick_sort_inplace(arr, low=0, high=None):if high is None:high = len(arr) - 1if 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  # i 是小于基准的区域的边界for j in range(low, high):if arr[j] <= pivot:i += 1arr[i], arr[j] = arr[j], arr[i]  # 交换元素arr[i + 1], arr[high] = arr[high], arr[i + 1]  # 将基准放到正确位置return i + 1  # 返回基准的最终位置# 测试
arr = [3, 6, 8, 10, 1, 2, 1]
quick_sort_inplace(arr)
print("Sorted array:", arr)关键步骤解析(以原地分区为例):
-  选择基准:通常选最后一个元素( arr[high])。
-  分区过程: -  指针 i标记小于基准的子数组的末尾。
-  遍历数组( j从low到high-1),若当前元素arr[j] <= pivot,则将其交换到i+1的位置。
-  最后将基准交换到 i+1的位置,此时基准左侧全小于它,右侧全大于它。
 
-  
-  递归:对左右子数组重复上述过程。 
时间复杂度分析:
-  最佳/平均情况:O(n log n) 每次分区将数组均匀分成两部分。 
-  最坏情况:O(n²) 当数组已有序且基准选择不当(如总是选最大/最小元素)。 
-  优化:随机选择基准可避免最坏情况: import random pivot_index = random.randint(low, high) arr[pivot_index], arr[high] = arr[high], arr[pivot_index] # 将随机基准移到末尾
特点总结:
-  不稳定排序:相同元素的相对位置可能改变。 
-  空间复杂度:递归栈深度 O(log n)(原地分区版本)。 
-  适用场景:大数据量且对稳定性无要求时效率高。 
通过理解分区过程和递归思想,可以轻松掌握快速排序的核心逻辑!
