I got the following algorithm and I am trying to figure out the complexity of it if i call max(a,1,n):

max(a,i,n)

if i<n then x=max(a,i+1,n)

else return(a[n])

if x<a[i] then return(x)

else return(a[i])

max(a,i,n)

if i<n then x=max(a,i+1,n)

else return(a[n])

if x<a[i] then return(x)

else return(a[i])

Do you have specific questions?

Do you have any work on this (incomplete even) that we can review?

I can tell you this much, the duration of the algorithm is proportional to the number of times it calls itself recusrively. So you need to figure out how many times the function calls itself.

i.e you will have a formula based on a, i, and n (it is possible that 1 or 2 of these might not appear in the formula) that tells you how many times max() will be called.

#include<iostream.h>

int max(int [],int,int);

main()

{

int a[5]={200,10,100,6,8};

int maxi;

maxi=max(a,0,4);

cout<<"The maximum is:"<<maxi;

return(0);

}

/*function founds the maximum number and returns it.Funtion goes through all the elements in the array and then compares them to find maximum.*/

max(int a[],int i,int n)

{

int x;

if(i<=n)

{ x=max(a,i+1,n);

}

else

{

return(a[n]);

}

if(x>a[i])

{

return(x);

}

else

return(a[i]);

}

All Courses

From novice to tech pro — start learning today.

the algorithm, has the form

max(int a[],int i,int n)

{

int x;

if(i<=n)

{

x=max(a,i+1,n); // The real work.

}

return something

}

(Take a look, after that recusive call, the algorithm just quickly returns a value in one of three ways, that is pretty fast, the slow part is calling itself again and again...)

So the question is, give particular values of i and n, how many times does it call itself recursively? Well, i starts out as the "low value" and one each call it increases by 1 until it reaches the "high value" (n). So you can see the function will be called recursively n-i+1 times.

so the function is O(n-i+1) which is pretty close to O(n-i).

This makes it a linear function, that is its run-time duration is linearly propotional tot he amount of data it must process. Double the data (double n and leave i 0) and the process takes twice as long...)