Data-Structures-and-Algorithms

My notes from an online C++ course


Project maintained by jfspps Hosted on GitHub Pages — Theme by mattgraham

Types of recursive functions

void fun(int n)
{
 if(n > 0)
 {
 printf("%d ", n); 
 fun(n - 1);
 }
}

Note this example is not a tail recursion because the final call is the + operator:

void fun(int n)
{
 if(n > 0)
 {
 printf("%d ", n); 
 fun(n - 1) + n;
 }
}

Tail and head recursion, with only one recursive call, are termed linear recursions. They generally have O(n) complexity.

void fun(int n)
{
 if (n > 0)
 {
  printf("%d ", n);
  fun(n - 1);
  fun(n - 1);
 }
}

Above, the output is “3, 2, 1, 1, 2, 1, 1”. The space complexity is (n + 1) which is O(n). A total of 15 calls were made for an element size of 3. It can be shown that the order follows a geometric progression, with worst-case degree of 2^(n+1) - 1, which is effectively O(2^n).

void A()
{
 if(...)
 {
 ...
 B();
 ...
 }
}

void B()
{
 if(...)
 {
 ...
 A();
 ...
 }
}
void fun(int n)
{
 if(...)
 {
 ...
 fun(fun(n-1));
 ...
 }
}