[英]Asymptotic Growth of Run Time of function with three nested for loops
I have pseudo code for a function (below). 我有一个函数的伪代码(如下)。
I understand that if each of i
, j
and k
were 1
then worst case run time would be O(n^3)
. 我知道,如果i
, j
和k
均为1
则最坏情况下的运行时间为O(n^3)
。 I am struggling to understand the impact of n/2
though - if any - on run time. 我正在努力理解n/2
对运行时的影响-如果有的话。 Any guidance would be great. 任何指导都会很棒。
for i=n/2; i < n; increase i by 1
for j=1; j < n/2; increase j by 1
for k = 1; k < n; increase k by k*2
Execute a Statement
Your understanding is not correct 您的理解不正确
k
is increased by k*2
which leads to logarithmic time, the complexity is actually O(n^2 * log n)
k
增加k*2
导致对数时间,复杂度实际上为O(n^2 * log n)
The O(n/2) = O(n)
, therefore the n/2
does not have any impact on asymptotic growth. O(n/2) = O(n)
,因此n/2
对渐近增长没有任何影响。
If you are not sure, the general approach is to count it as precise as possible and then remove the constants. 如果不确定,通常的方法是尽可能精确地计数,然后删除常量。
for i
will be execute n/2
times, the for j
also n/2
times and k
will be executed log n
times. for i
将被执行n/2
次, for j
也n/2
倍和k
将被执行log n
次。
n/2 * n/2 * log n = (n^2/4) * log n
. n/2 * n/2 * log n = (n^2/4) * log n
。 You can remove constants, so O(n^2 * log)
您可以删除常量,因此O(n^2 * log)
The worst case time complexity is not O(N^3)
最坏的情况下时间复杂度不是O(N^3)
Check the innermost for loop. 检查最里面的循环。 K
increases by K * 2
That means, the innermost for loop will take O(lgN)
time K
增加K * 2
意味着最里面的for循环将花费O(lgN)
时间
Other two outer loops would take O(N)
time each and N/2
would not have any effect on the asymptotic growth of run time. 其他两个外部循环每个都需要O(N)
时间,而N/2
对运行时间的渐近增长没有任何影响。
So, the overall time complexity would be O(N^2 * lgN)
因此,整体时间复杂度为O(N^2 * lgN)
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.