[英]Find complexity of the following recurrence: T(n) = T(n/2) + log(n)
How can I estimate the run time of two loops, where each runs in a logarithmic time, as shown here: 我如何估计两个循环的运行时间,每个循环以对数时间运行,如下所示:
for(int i=n; i>=0; i /= 2)
{
for( int j=i; j>=0; j /= 2)
{
count++;
}
}
My analysis: 我的分析:
i = n , 1 => j = lg n | 1+lg (n)
i = n/2, 1 => j = lg n/2 | 1+lg (n/2)
i = 1 , 1 => j = 0 | 1
How to sum up the logarithmic term in this case? 在这种情况下如何总结对数项?
i = n. | Inner loop runs log(n) iterations. | O(log(n))
i = n/2. | Inner loop runs log(n/2) iterations. | O(log(n))
i = n/4. | Inner loop runs log(n/4) iterations. | O(log(n))
. | |
. | |
i = log(n). | Inner loop runs log(log(n)) iterations. | O(log(log(n)))
What are we noticing ? 我们注意到了什么? that for each
n
we are adding O(log(n))
我们每个
n
都添加O(log(n))
This recurrence is T(n) = T(n/2) + log(n) + 1
Which can be expanded the following way: 这种重现是
T(n) = T(n/2) + log(n) + 1
可以通过以下方式扩展:
T(n) = log(n) + log(n/2) + log(n/4) + ... + 1
= log(n) + [log(n)-1] + [log(n)-2] + [log(n) - 3] + .... + 1
= log(n)*log(n) - (2 + 3 + .... log(n))
= log(n)*log(n) - ([(2+log(n))*log(n)]/2)
= log(n)*log(n) - ~0.5log(n)*log(n)
= ~0.5log(n)*log(n)
T(n) = O(log(n)*log(n))
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.