[英]Is this loop O(nlog(n))?
I have a nested for loop that I am trying to analyze the efficiency of. 我有一个嵌套的for循环,我正在尝试分析其效率。 The loop looks like this:
循环如下所示:
int n = 1000;
for (int i = 0; i < n; i++) {
for (int j = 0; j < i; j++) {
System.out.print("*");
}
}
I don't believe that this algorithm is O(n^2) because the inner loop does not run n times, it only runs i times. 我不认为该算法是O(n ^ 2),因为内部循环不会运行n次,它只会运行i次。 However, it certainly is not O(n).
但是,肯定不是O(n)。 So I hypothesize that it must be between the two efficiencies, which gives O(nlog(n)).
因此,我假设它必须介于两个效率之间,即为O(nlog(n))。 Is this accurate or is it really a O(n^2) algorithm and I'm misunderstanding the effect the inner loop has on the efficiency?
这是准确的还是真的是O(n ^ 2)算法,并且我误解了内循环对效率的影响?
Your algorithm will run a triangular number of times: 您的算法将运行三角形次数:
n * (n + 1) / 2
n *(n + 1)/ 2
In the above case, n = 999
because the first j
loop doesn't run: 在上述情况下,
n = 999
因为第一个j
循环未运行:
(999 * 1000) / 2 = 499500
(999 * 1000)/ 2 = 499500
It is lower than n**2
, but it still is O(n**2)
, because n * (n + 1) / 2
is n**2 / 2 + n / 2
. 它低于
n**2
,但仍为O(n**2)
,因为n * (n + 1) / 2
为n**2 / 2 + n / 2
。 When n
is large, you can ignore n / 2
compared to n**2 / 2
, and you can also ignore the constant 1 / 2
factor. 当
n
大时,与n**2 / 2
n / 2
相比,您可以忽略n / 2
,并且也可以忽略常数1 / 2
。
I kind of get your doubts, but try to think in this way: what value will i
have in the worst case scenario? 我有点让您怀疑,但请尝试以这种方式思考:在最坏的情况下,
i
将具有什么价值? Answer is n-1
, right? 答案是
n-1
对吗? So, as the complexity is evaluated by considering the worst case scenario it turns out that it is O(n^2)
as n * (n-1) ~ n^2
. 因此,当通过考虑最坏情况来评估复杂度时,结果证明它是
O(n^2)
为n * (n-1) ~ n^2
。
The number of iterations is sum from i=0 to n-1 (sum from j=0 to i-1 (1))
. 迭代次数是
sum from i=0 to n-1 (sum from j=0 to i-1 (1))
。 The inner sum is obviously equal to i
. 内部和显然等于
i
。 sum from i=0 to n-1 (i) = n * (n-1) / 2 = O(n^2)
is well known. sum from i=0 to n-1 (i) = n * (n-1) / 2 = O(n^2)
是众所周知的。
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.