1 2 3 4 5 |
|
What is the time complexity of the above function?
This section requires Javascript.
You are seeing this because something didn't load right. We suggest you, (a) try
refreshing the page, (b) enabling javascript if it is disabled on your browser and,
finally, (c)
loading the
non-javascript version of this page
. We're sorry about the hassle.
Let's think above this intuitively, without using induction. We let T ( n ) denote the running time of our algorithm for an input of size n .
Clearly, our algorithm is recursive, as we see the procedure f u n contains two calls to itself on smaller inputs. Thus, the running time may be expressed in terms of the running time on smaller inputs. Thus we may express our running time as the recurrence T ( n ) = T ( n − 1 ) + T ( n − 1 ) + O ( 1 ) = 2 T ( n − 1 ) + O ( 1 ) , where we use O ( 1 ) since the amount of work required by each recursive call is constant (the amount of time needed to make the recursive call, and the mount of time required to combine the solution to the recursive call into the solution for the larger problem, since addition may be thought of as a constant operation on reasonably small integers).
Now, our algorithm will always reduce each subproblem into two smaller subproblems, each one less than the prior subproblem, until the boundary condition of the recurrence is reached (that is, when n = 1 . So then let us ask, how many times may we subtract 1 from n until we get to 1 ? The answer is n − 1 times.
We can then think of our recurrence as T ( n ) = 2 T ( n − 1 ) + O ( 1 ) = 2 ( 2 ( T ( n − 2 ) ) + O ( 1 ) + O ( 1 ) = ⋯ = 2 n − 1 T ( 1 ) + ( n − 1 ) ⋅ O ( 1 ) .
Simplifying gives T ( n ) = 2 n − 1 T ( 1 ) + n O ( 1 ) − O ( 1 ) = O ( 2 n − 1 ) = O ( 2 n ) .