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] 
        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.

  • $\begingroup$ General solutiom is called Mastert theorem: en.wikipedia.org/wiki/Master_theorem $\endgroup$ – tumdum Oct 18 '16 at 6:56
  • $\begingroup$ Still don't understand how I would use that in this scenario. Could you calculate the time complexity of the algorithm above? $\endgroup$ – learnerX Oct 18 '16 at 6:58
  • $\begingroup$ @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? $\endgroup$ – Shubham Singh rawat Oct 18 '16 at 7:32
  • $\begingroup$ 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. $\endgroup$ – learnerX Oct 18 '16 at 7:54
  • 1
    $\begingroup$ Duplicate of this and this $\endgroup$ – adrianN Oct 18 '16 at 8:38

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.

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

Not the answer you're looking for? Browse other questions tagged or ask your own question.