【面试】介绍快速排序及其时间复杂度(中英)

中文版

快速排序(Quick Sort) 是一种基于分治法的高效排序算法。它的基本思想是选择一个“基准”(Pivot)元素,通过一次排序将待排序数组分为两个部分,其中一部分所有元素都小于基准,另一部分所有元素都大于基准。然后,递归地对这两部分进行快速排序。具体步骤如下:

  1. 选择基准:从数组中选择一个元素作为基准(通常选择第一个元素、最后一个元素或随机选择)。
  2. 分区(Partitioning):重排数组,使得所有小于基准的元素位于基准的左边,所有大于基准的元素位于基准的右边。基准元素最终位于其正确的位置。
  3. 递归排序:分别对基准左右的子数组递归地应用快速排序。
时间复杂度:
  • 平均时间复杂度:快速排序的平均时间复杂度为 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:

  1. Choosing a Pivot: A pivot element is selected from the array (commonly the first element, the last element, or chosen randomly).
  2. 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.
  3. 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.
  • 20
    点赞
  • 4
    收藏
    觉得还不错? 一键收藏
  • 0
    评论
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值