Question 5 on Determining complexity for recursive functions (Big O notation) is:
int recursiveFun(int n)
{
for(i=0; i<n; i+=2)
// Do something.
if (n <= 0)
return 1;
else
return 1 + recursiveFun(n-5);
}
To highlight my question, I'll change the recursive parameter from n-5
to n-2
:
int recursiveFun(int n)
{
for(i=0; i<n; i+=2)
// Do something.
if (n <= 0)
return 1;
else
return 1 + recursiveFun(n-2);
}
I understand the loop runs in n/2
since a standard loop runs in n
and we're iterating half the number of times.
But isn't the same also happening for the recursive call? For each recursive call, n
is decremented by 2. If n
is 10, call stack is:
recursiveFun(8)
recursiveFun(6)
recursiveFun(4)
recursiveFun(2)
recursiveFun(0)
...which is 5 calls (i.e. 10/2
or n/2
). Yet the answer provided by Michael_19 states it runs in n-5
or, in my example, n-2
. Clearly n/2
is not the same as n-2
. Where have I gone wrong and why is recursion different from iteration when analyzing for Big-O?