【问题标题】:A basic confusion on quicksort快速排序的基本混淆
【发布时间】:2013-06-05 15:25:52
【问题描述】:

假设我们在快速排序的情况下选择一个枢轴作为数组的第一个元素。现在最好/最坏情况复杂度是O(n^2),而平均情况下是O(nlogn)。是不是很奇怪(最佳情况复杂度大于最坏情况复杂度)?

【问题讨论】:

  • 最好的情况是O(nlogn),而不是O(n^2)

标签: algorithm sorting quicksort


【解决方案1】:

最好的情况复杂度是O(nlogn),作为平均情况。最坏的情况是O(n^2)。检查http://en.wikipedia.org/wiki/Quick_sort

虽然合并排序和堆排序等其他算法具有更好的最坏情况复杂度 (O(nlogn)),但通常快速排序更快 - 这就是为什么它是最常用的排序算法。一个有趣的答案可以在Why is quicksort better than mergesort?找到。

【讨论】:

    【解决方案2】:

    The best-case of quicksort 0(nlogn) is when the chosen pivot splits the subarray in two +- equally sized parts in every iteration.

    Worst-case of quicksort is when the chosen pivot is the smallest element in the subarray, so that the array is split in two parts where one part consists of one element (the pivot) and the other part of all the other elements的子数组。

    因此,选择第一个元素作为已排序数组中的枢轴,将获得0(n^2)。 ;)

    因此,选择一个好的支点很重要。例如,使用子数组的第一个、中间和最后一个元素的中值作为枢轴。

    【讨论】:

      猜你喜欢
      • 2012-02-18
      • 1970-01-01
      • 2019-06-30
      • 2011-01-08
      • 2013-12-08
      • 1970-01-01
      • 2015-03-13
      • 2020-04-22
      • 1970-01-01
      相关资源
      最近更新 更多