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))
This recurrence is T(n) = T(n/2) + log(n) + 1
Which can be expanded the following way:
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))
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With