简体   繁体   中英

what the Time Complexity of T(n) = 2T(n/2) +O(1)

i want to know what the Time Complexity of my recursion method : T(n) = 2T(n/2) + O(1) i saw a result that says it is O(n) but i don't know why , i solved it like this :

T(n) = 2T(n/2) + 1
T(n-1) = 4T(n-1/4) + 3
 T(n-2) = 8T(n-2/8) + 7
......  …………..  ..
T(n) = 2^n+1 T (n/2^n+1) + (2^n+1 - 1) 

Consider that n=2^m , which allows you to write

T(2^m)=2T(2^(m-1))+O(1)

or by denoting S(m):= T(2^m) ,

S(m)=2 S(m-1) + O(1),

2^m S(m)=2 2^(m-1)S(m-1) + 2^(m-1) O(1)

and finally,

R(m) = R(m-1) + 2^(m-1) O(1).

Now by induction,

R(m) = R(0) + (2^m-1) O(1),

T(n) = S(m) = 2^(1-m) T(2^m) + (2 - 2^(m-1)) O(1) = 2/n T(n) + (2 - n/2) O(1).

I think you have got the wrong idea about recursive relations. You can think as follows:

If T(n) represents the value of function T() at input = n then the relation says that output is one more double the value at half of the current input. So for input = n-1 output ie T(n-1) will be one more than double the value at half of this input, that is T(n-1) = 2*T((n-1)/2) + 1

The above kind of recursive relation should be solved as answered by Yves Daoust. For more examples on recursive relations, you can refer this

There are a couple of rules that you might need to remember. If you can remember these easy rules then Master Theorem is very easy to solve recurrence equations. The following are the basic rules which needs to be remembered

case 1) If n^(log b base a) << f(n) then T(n) = f(n)
case 2) If n^(log b base a) = f(n) then T(n) = f(n) * log n
case 3) 1) If n^(log b base a) >> f(n) then T(n) = n^(log b base a)

Now, lets solve the recurrence using the above equations.

a = 2, b = 2, f(n) = O(1)
n^(log b base a) = n = O(n)

This is case 3) in the above equations. Hence T(n) = n^(log b base a) = O(n).

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM