Reputation: 13
void f(int n)
{
doOh(n);
if(n<1) return;
for(int i=0; i<2; i++)
{
f(n/2);
}
}
Time complexity of doOh(n) is O(N). How can we compute the time complexity of the given function.
Upvotes: 0
Views: 107
Reputation:
Denoting the complexity as T(n)
, the code says
T(n) = T0 if n = 0
= O(n) + 2 T(n/2) otherwise
We can get an upper bound by replacing O(n)
with c n
for some c
*, and we expand
T(n) = c n + 2 T(n/2)
= c n + 2 c n/2 + 4 T(n/4)
= c n + 2 c n/2 + 4 c n/4 + 8 T(n/8)
= ...
The summation stops when n < 2^l
, where l
is the number of significant bits of n
. Hence we conclude that
T(n) = O(l c n + 2^l T0) = O(l n).
*Technically, we can only do that as of n >
some N
. But this does not change the conclusion regarding the asymptotic behavior of T
.
Upvotes: 1
Reputation: 377
Complexity = O(nlog2n)
The reason is
Upvotes: 0