简体   繁体   English

关于您计算它的方式,冒泡排序算法的时间复杂度如何导致 O(n^2)?

[英]How does the time complexity of the bubble sort algorithm result in O(n^2) regarding the way you calculate it?

I understand that why bubble sort is O(n^2).我明白为什么冒泡排序是 O(n^2)。

However in many explanations I see something like this:然而,在许多解释中,我看到了这样的事情:

(n-1) + (n-2) + (n-3) + ..... + 3 + 2 + 1
Sum = n(n-1)/2

How do you calcuate Sum from this part:您如何从这部分计算Sum

(n-1) + (n-2) + (n-3) + ..... + 3 + 2 + 1

Can anyone help?任何人都可以帮忙吗?

Here's the trick:这是诀窍:

If n is even:
  n + (n-1) + (n-2) + … + 3 + 2 + 1
= [n + 1] + [(n-1) + 2] + [(n-2) + 3] + … + [(n - (n/2 - 1)) + n/2]
= (n + 1) + (n + 1) + (n + 1) + … + (n + 1)
= n(n+1)/2

If n is odd:
  n + (n-1) + (n-2) + … + 3 + 2 + 1
= [n + 1] + [(n-1) + 2] + [(n-2) + 3] + … + [(n - (n-1)/2 + 1) + (n-1)/2] + (n-1)/2 + 1
= (n+1) + (n+1) + (n+1) + … + (n+1) + (n-1)/2 + 1
= (n+1)(n-1)/2 + (n-1)/2 + 1
= (n^2 - 1 + n - 1 + 2)/2
= (n^2 + n)/2
= n(n+1)/2

For your case, since you're counting up to n-1 rather than n, replace n with (n-1) in this formula, and simplify:对于您的情况,由于您最多计数 n-1 而不是 n,因此请在此公式中将 n 替换为 (n-1) 并简化:

   x(x+1)/2, x = (n-1)
=> (n-1)((n-1)+1)/2 
 = (n-1)(n)/2 
 = n(n-1)/2

The simplest "proof" to understand without deriving the equation is to imagine the complexity as area:无需推导方程即可理解的最简单的“证明”是将复杂性想象为面积:

so if we have sequence:所以如果我们有序列:

n+(n-1)+(n-2)...

we can create a shape from it... let consider n=5 :我们可以从中创建一个形状......让我们考虑n=5

n     5     *****
n-1   4     ****
n-2   3     ***
n-3   2     **
n-4   1     *

Now when you look at the starts they form a right angle triangle with 2 equal length sides... that is half of nxn square so the area is:现在,当您查看起点时,它们形成了一个具有 2 个等长边的直角三角形......这是nxn正方形的一半,因此面积是:

area = ~ n.n / 2 = (n^2)/2

In complexities the constants are meaningless so the complexity would be:在复杂性中,常数是没有意义的,所以复杂性是:

O(n^2)

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

相关问题 如何计算冒泡排序时间复杂度 - how to calculate Bubble sort Time Complexity 这个算法的时间复杂度是 O(n) 还是 O(n^2)? - Does this algorithm have time complexity of O(n) or O(n^2)? 如何证明算法的时间复杂度为O(2 ^ n)? - How to show that the time complexity of algorithm is O(2^n)? 该算法的复杂度如何为 O(n^2)? - How does this algorithm have complexity of O(n^2)? 是否存在一种稳定的排序算法,可以对 O(n) 时间复杂度和 O(1) 辅助空间复杂度的二进制数组进行排序? - Does there exist a stable sorting algorithm that can sort a binary array in O(n) time complexity and O(1) auxiliary space complexity? 例如,在此插入排序算法中,如何证明算法的时间复杂度为O(n ^ 2)? - In this insertion sort algorithm for example, how would I prove the algorithm's time complexity is O(n^2)? 这个算法的时间和空间复杂度是 O(n) 还是 O(1)? - Does this algorithm have time and space complexity O(n) or O(1)? 为什么以下算法的时间复杂度(循环排序?!)是O(n)? - Why time complexity of following algorithm(cycle sort?!) is O(n)? 该算法的时间复杂度是否为O(N ^ 2)? - Is the time complexity of this algorithm O(N^2)? 冒泡排序算法求时间复杂度 - bubble sort algorithm find time complexity
 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM