中文版
快速排序(Quick Sort) 是一种基于分治法的高效排序算法。它的基本思想是选择一个“基准”(Pivot)元素,通过一次排序将待排序数组分为两个部分,其中一部分所有元素都小于基准,另一部分所有元素都大于基准。然后,递归地对这两部分进行快速排序。具体步骤如下:
- 选择基准:从数组中选择一个元素作为基准(通常选择第一个元素、最后一个元素或随机选择)。
- 分区(Partitioning):重排数组,使得所有小于基准的元素位于基准的左边,所有大于基准的元素位于基准的右边。基准元素最终位于其正确的位置。
- 递归排序:分别对基准左右的子数组递归地应用快速排序。
时间复杂度:
- 平均时间复杂度:快速排序的平均时间复杂度为 O ( n log n ) O(n \log n) O(nlogn),其中 n n n 是待排序元素的数量。通常情况下,快速排序能将数组均匀地分为两部分,因此效率很高。
- 最坏时间复杂度:在最坏情况下(例如每次选择的基准都是当前数组的最大或最小值),时间复杂度为 O ( n 2 ) O(n^2) O(n2),因为每次分区只能减少一个元素。
- 最优时间复杂度:在理想情况下(每次分区都能将数组均分),时间复杂度为 O ( n log n ) O(n \log n) O(nlogn)。
- 空间复杂度:快速排序的空间复杂度为 O ( log n ) O(\log n) O(logn),主要是递归调用栈的空间消耗。通过尾递归优化,可以将空间复杂度进一步降低。
English Version
Quick Sort is an efficient sorting algorithm based on the divide-and-conquer principle. The basic idea is to select a “pivot” element and then partition the array into two parts: one part with elements smaller than the pivot and the other with elements larger than the pivot. The quicksort algorithm is then recursively applied to these two parts. The steps are as follows:
- Choosing a Pivot: A pivot element is selected from the array (commonly the first element, the last element, or chosen randomly).
- Partitioning: The array is rearranged so that all elements less than the pivot are on its left, and all elements greater than the pivot are on its right. The pivot element ends up in its correct position.
- Recursive Sorting: The quicksort algorithm is then recursively applied to the sub-arrays on the left and right of the pivot.
Time Complexity:
- Average Time Complexity: The average time complexity of quicksort is O ( n log n ) O(n \log n) O(nlogn), where n n n is the number of elements to be sorted. Typically, quicksort can divide the array into two nearly equal parts, making it highly efficient.
- Worst Time Complexity: In the worst case (e.g., when the pivot is always the smallest or largest element), the time complexity can degrade to O ( n 2 ) O(n^2) O(n2) because each partition only reduces the array by one element.
- Best Time Complexity: In the best case (ideal partitioning), the time complexity is O ( n log n ) O(n \log n) O(nlogn).
- Space Complexity: The space complexity of quicksort is O ( log n ) O(\log n) O(logn), primarily due to the recursive call stack. Tail recursion optimization can further reduce space usage.