# What is the time complexity (upper bound) for this simple recursive function? [duplicate]

This question already has an answer here:

So I have function that I have written to return the maximum value between index i and index x of a given array using recursion as follows:

FindMax( A, i, j )
if (i == j):
return A[i]
else:
k = (i + j) / 2
return max( FindMax(A, i, k), FindMax(A, k+1, j) )


What is the correct way to go about calculating the big O asymptotic time complexity of this algorithm? I would appreciate if someone could document a general way to calculate the correct complexity even if it is a different recursive function. I have spent a lot of time watching videos and reading up on the web but sadly I come up with different complexities after each.

## marked as duplicate by adrianN, David Richerby, Raphael♦Oct 18 '16 at 9:37

This question has been asked before and already has an answer. If those answers do not fully address your question, please ask a new question.

• General solutiom is called Mastert theorem: en.wikipedia.org/wiki/Master_theorem – tumdum Oct 18 '16 at 6:56
• Still don't understand how I would use that in this scenario. Could you calculate the time complexity of the algorithm above? – learnerX Oct 18 '16 at 6:58
• @learnerX As you mentioned this is a recursive procedure , for time complexity try to figure out the the recurrence relation for the code first. For the same calculate the sub problem size and number of steps taken at each recursive step. Can you take it from here? – Shubham Singh rawat Oct 18 '16 at 7:32
• That is the approach that I am trying to follow. Find a recurrence relation and then keep decreasing it until f(n=0 or 1), the base case. Could you show me how to actually do that though? That would help since I'm having trouble doing that. – learnerX Oct 18 '16 at 7:54
• Duplicate of this and this – adrianN Oct 18 '16 at 8:38

## 1 Answer

Let's say the time of FindMax is $T(n)$ where $n$ is the size of array A. Notice, that FindMax access only the part of array between $i$ and $j$. Look at the pseudocode step by step. The first if is just comparison, so it's O(1). IF comparison is true, returning is O(1) (exit recursion step). The else step is doing again some arithmetic things which is O(1) and then calling three functions: max with time O(1), FindMax with time $T(n/2)$ and again FindMax. The time is the half, because again those function are "working" on the half of the original array. This gives the recursion $T(n) = O(1) + 2T(n/2)$. Using the master's theorem we get $T(n) = O(n)$ see here. Another proof without using the theorem mentioned above is by induction, pretty straightforward for this relation.

• Welcome to Computer Science! Please consider not to encourage undesirable posting behaviour. We have reference material to help users with such questions (see above). – Raphael Oct 18 '16 at 9:38