简体   繁体   English

算法的最坏情况时间复杂度与其上限之间的关系/差异是什么?

[英]What is the relation/difference between worst case time complexity of an algorithm and its upper bound?

算法的最坏情况时间复杂度与其上限之间的关系/差异是什么?

The term "upper bound" is not very clear, as it may refer to two possible things: 术语“上限”不是很清楚,因为它可能指的是两个可能的东西:

  1. The upper bound of the algorithm - the bound where the algorithm can never run "slower" than it. 算法的上限 - 算法永远不会比它运行“慢”的界限。 This is basically the worst case performance of it, so if this is what you mean - the answer is pretty simple. 这基本上是它最差的表现,所以如果这就是你的意思 - 答案很简单。

  2. big-O notation, which provides an upper bound on the complexity of the algorithm under a specific analysis. big-O表示法,它在特定分析下提供算法复杂性的上限。 The big-O notation is a set of functions , and can be applied to any analysis of an algorithm, including worst case, average case, and even best case. big-O表示法是一函数 ,可以应用于算法的任何分析,包括最坏情况,平均情况,甚至最佳情况。

Let's take Quick Sort as an example. 我们以快速排序为例。

Quick Sort is said to have O(n^2) worst case performance, and O(nlogn) average case performance. 据说Quick Sort具有O(n^2)最差情况性能和O(nlogn)平均案例性能。 How can one algorithm has two complexities? 一种算法如何具有两种复杂性? Simple, the function representing the analysis of average case, and the one representing the worst case, are completely different funcitons - and we can apply big O notation on each of them, there is no restriction about it. 简单来说,表示平均情况分析的函数和表示最坏情况的函数是完全不同的函数 - 我们可以对它们各自应用大O表示法,对它没有限制。

Moreover, we can even apply it to best-case. 而且,我们甚至可以将它应用于最佳情况。 Consider a small optimization to quick-sort, where it first checks if the array is already sorted, and if it is - it stops immidiately. 考虑一个小的优化来快速排序,它首先检查数组是否已经排序,如果是 - 它会立即停止。 This is effectively O(n) operation, and there is some input that will provide this behavior - so we can now say that the algorithm's best case complexity is O(n) 这实际上是O(n)操作,并且有一些输入将提供这种行为 - 所以我们现在可以说算法的最佳案例复杂度是O(n)

The difference between worst case and big O(UPPER BOUND) is that the worst case is a case that actually happens to your code, the upper bound is an overestimate, an assumption that we put in order to calculate the big O, it doesn't have to happen 最坏的情况下,大O(上限)之间的区别是, 最坏的情况是实际发生在你的代码情况下, 上限是高估了,我们把以计算大O的假设,这不是”必须发生

example on insertion sort: 关于插入排序的示例:

Worst Case: 最差的情况:

The numbers are all arranged reversely so you need to arrange and move every single number 这些数字都是相反排列的,所以你需要安排和移动每一个数字

Pseudo-code 伪代码

for j=2 to n
  do key = a[i]
  i=j-1
  while i>0 & a[i]>key
    do a[i+1] = a[i]
    i=i-1
  end while
  a[i+1]=key
end for

Upper Bound: 上界:

We assume that the order of the inner loop is i =n-1 every single time, but in fact, it is changeable every time, it can't be n-1 every time, but we assumed /overestimated it to calculate the big O 我们假设内循环的顺序每次都是i = n-1,但事实上,它每次都是可变的,每次都不能是n-1,但我们假设/高估它来计算大Ø

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM