[英]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.