## 1. Introduction

In the first part of this article, we studied different types of recursion and their implementation using C++ [5]. We studied recursion from two different dimensions; first, it is either performed at compile time or at run time, second, we discussed five different types of recursion. Now we are going to study recursion again with one more dimension.

## 2. Recursion Type

Recursion can also be classified by Structure Recursion and Generative Recursion. The main difference between these is, Generative recursion usually decomposes the original problem into sub problems to solve it. For example, to calculate the factorial of a given number, we calculate the factorial of a number one less than the given number and keep doing this until we reach the termination condition. In the case of binary search, we divided the given array into two pieces and run the binary search on that. In this case, we eliminate half of the elements during every recursive call until we either found the required element or reach a point where we have only one element left. Now if that element is required then we found it at after Log_{2} (n) comparison (i.e. worst case); where “n” is the total number of elements in an array.

On the other hand Structure recursion usually performs data rather than decomposing the problem into smaller pieces. We can store data in recursive structures such as Binary Tree and in that case it would be natural to use recursion to perform operations on it. Structure recursion is not only limited to recursive data structure, but it would be very handy in some linear structures such as Link List.

In my previous article [5] we studied two dimensions of recursion i.e. recursion types such as linear, tail, binary, etc and whether it happens at compile time or at run time. Here we added one more dimension in it i.e. structure recursion and generative recursion, and now we are going to study them.

First we are going to study the compile time and run time variant of structure and generative programming. For the compile time version we are again going to study the meta-programming template. In fact, we have already studied the generative compile time recursion in the previous article. Almost all of the template meta-programming examples given in the previous article are also examples of generative recursion.

We can define this relationship with simple block diagrams. This diagram is very much similar to one we have already seen in previous article.

The syntax of template meta-programming is still most confusing to even an experienced C++ developer until he/she gets his/her hands dirty with it a little bit. Therefore, I decided to use the same example for compile time and run time recursion for an easier comparison between these two.

### 2.1. Run Time Structure Recursion

I decide to select the link list as an example to discuss runtime and compile time structure recursion. The main reason for this is, it is very easy to implement and understand.

Here is a simple structure of a node of link list. Although this node contains only one data element, but it can be easily extend to store as much information as you like.

struct Node
{
int value;
Node* next;
};

Before we actually start playing with link lists it would be helpful to make a function to add items in the link list. Here is one simple function to add the values in the link list. This implementation is not the world's best implementation of add values in the link list (what will be the case when there isn’t enough memory to allocate a new node?) but for our purpose this can be a good candidate for proof of concept.

void AddNode(Node** pHead, int value)
{
if (*pHead == NULL)
{
*pHead = new Node();
(*pHead)->value = value;
(*pHead)->next = NULL;
}
else
{
Node* pTemp = *pHead;
while (pTemp != NULL)
{
pTemp = pTemp->next;
}
pTemp = new Node();
pTemp->value = value;
pTemp->next = *pHead;
*pHead = pTemp;
}
}

Now we have enough tools to start playing with it. Here are a few examples of traversing a Single Link List recursively. If you take a close look then you may notice that all of these examples are also types of tail recursion, which we already studied in the previous episode. We can even call these examples “Runtime time, Structure, Tail Recursion.”

int Count(Node* pHead, int iCount = 0)
{
if (pHead == NULL)
return iCount;
else
return Count(pHead->next, ++iCount);
}
int Add(Node* pHead, int iSum = 0)
{
if (pHead == NULL)
return iSum;
else
return Add(pHead->next, pHead->value + iSum);
}
int Multiply(Node* pHead, int iMultiply = 1)
{
if (pHead == NULL)
return iMultiply;
else
return Multiply(pHead->next, pHead->value * iMultiply);
}

Here is the usage of these functions

Node* pHead = NULL;
AddNode(&pHead, 15);
AddNode(&pHead, 20);
AddNode(&pHead, 35);
std::cout << Count(pHead) << std::endl;
std::cout << Add(pHead) << std::endl;
std::cout << Multiply(pHead) << std::endl;

### 2.2. Compile Time Structure Recursion

Here we are going to look at the Compile time version of all of these programs. The compile time version of these examples are even more fun, because here we are going to create a data structure at compile time, i.e. Compile Time Data Structure. Compile Time Data Structure is in fact not a new concept in C++. Further information about it can be found in [1][3]. Here is the compile time equivalent of what we already studied in the previous example.

struct End
{
};
template <int iData, typename Type>
struct Node
{
enum { value = iData };
typedef Type Next;
};

Here we need one more structure to indicate the termination condition of the link list. You can also say it is an end marker. In the run time version we don’t need any such concept because in that case we simply check the value of next field in the node. If its value is NULL then it means that it is the last node of the link list.

However, in the case of a meta-programming template, we have to do template specialization (or partial template specialization) to stop the recursion. We can do template specialization for any specific type or for any specific value. Here we can’t do template specialization on a value, because the second template parameter is type. Therefore, we have to create one new type to stop the recursive instantiation of template. The name of the end marker can be anything and it can store whatever you like. In our example it would be sufficient to make one empty structure to create a new type as an end marker.

Now the fun part begins. Here are few example of traversing static link list at compile time using recursive template instantiation. In first example we are going to calculate the length of the static link list, in second we add the items of the static link list and in third we multiply the items in the static link list. These examples are compile-time version of the same thing we studied in previous section. Therefore we can say these examples are “Compile time, Structure, Tail Recursion”.

template <typename T>
struct Add;
template <int iData, typename Type>
struct Add<Node<iData, Type> >
{
enum { value = iData + Add<Type>::value };
};
template <>
struct Add<End>
{
enum { value = 0 };
};
template <typename T>
struct Length;
template <int iData, typename Type>
struct Length<Node<iData, Type> >
{
enum { value = 1 + Length<Type>::value };
};
template <>
struct Length<End>
{
enum { value = 0 };
};
template <typename T>
struct Multiply;
template <int iData, typename Type>
struct Multiply<Node<iData, Type> >
{
enum { value = iData * Multiply<Type>::value };
};
template <>
struct Multiply<End>
{
enum { value = 1 };
};

Here is the usage of static link list.

typedef Node<15, Node<20, Node<35, End> > > staticList;
std::cout << Length<staticList>::value << std::endl;
std::cout << Add<staticList>::value << std::endl;
std::cout << Multiply<staticList>::value << std::endl;

### 2.3. Run Time Generative Recursion

Here is an example of Generative Runtime recursion. Suppose we want to calculate number of digits in a given number then we can calculate it by dividing the original number by 10 until it becomes less than 10 and count all the divisions. For example, if the given number is 34253 then the first time when we divide this number by 10 we will get 3425, (here we are storing the result in integer variable, therefore, we don’t care about the floating point values). Subsequently we will get 342, 34 and 3.

We can implement this problem more than one way; the most obvious ones are looping and recursion. Even in recursion we can use different recursive techniques to do this. Here we are going to solve this problem with tail recursion.

int CountDigit(int no, int a = 1)
{
if (no < 10)
return a;
else
return CountDigit(no / 10, ++a);
}

### 2.4. Compile Time Generative Recursion

As we have seen in the previous article that most of the time when we are discussing recursion we usually also mention the mathematical equation too, but this is not the case in the previous example. There can be several other good mathematical examples to discuss generative and structure recursion with compile time and run time variant. But there is one very good reason to select that example. This example has more than one termination condition to stop recursion. As we have seen in the run time version of this problem, the termination condition is when the input number is less than 10 no matter if it is 0, 1, 2 or any other number less than 10.

Here is our first attempt to solve this problem using a naïve approach. Here we created a specialization class for all the termination condition.

template <int no, int a>
struct CountDigit
{
enum { value = CountDigit<no / 10, (a+1)>::value };
};
template <int a>
struct CountDigit<0, a>
{
enum { value = a };
};
template <int a>
struct CountDigit<1, a>
{
enum { value = a };
};
template <int a>
struct CountDigit<2, a>
{
enum { value = a };
};
template <int a>
struct CountDigit<3, a>
{
enum { value = a };
};
template <int a>
struct CountDigit<4, a>
{
enum { value = a };
};
template <nt a>
struct CountDigit<5, a>
{
enum { value = a };
};
template <int a>
struct CountDigit<6, a>
{
enum { value = a };
};
template <int a>
struct CountDigit<7, a>
{
enum { value = a };
};
template <int a>
struct CountDigit<8, a>
{
enum { value = a };
};
template <int a>
struct CountDigit<9, a>
{
enum { value = a };
};

Here is an example of its usage

std::cout << CountDigit<1234, 1>::value << std::endl;
std::cout << CountDigit<8, 1>::value << std::endl;
std::cout << CountDigit<23, 1>::value << std::endl;
std::cout << CountDigit<43565, 1>::value << std::endl;
std::cout << CountDigit<123, 1>::value << std::endl;

There are two major problems with this version. The first one is, of course, writing almost the same code for every condition. The second one is even more severe. This program doesn’t truly reflect the run time counterpart. Here we assumed that the only positive numbers are less than 10 and completely ignore the negative numbers. This program will produce incorrect results if we are going to use this with a negative number.

This problem is very serious to handle, because all negative numbers are less than 10 and to make this program work on all negative numbers we have to make infinite specialization classes.

Here is our first approach to solving both problems. In the next program we are going to use the preprocessor macro to automatically generate the template specialization classes for us. At the same time we also try to attack the infinite template specialization classes by restricting it to only 19 cases (9 for positive numbers, 9 for negative numbers and one for zero). Because we know that if we keep dividing any number (positive or negative) by 10 then eventually we will get the single digit number in the range of -9 to 9.

#define COUNTDIGIT_SPECIALIZATION(X) \
template <int a> \
struct CountDigit<X, a> \
{ \
enum { value = a }; \
};
template <int no, int a>
struct CountDigit
{
enum { value = CountDigit<no / 10, (a+1)>::value };
};
COUNTDIGIT_SPECIALIZATION(0)
COUNTDIGIT_SPECIALIZATION(1)
COUNTDIGIT_SPECIALIZATION(2)
COUNTDIGIT_SPECIALIZATION(3)
COUNTDIGIT_SPECIALIZATION(4)
COUNTDIGIT_SPECIALIZATION(5)
COUNTDIGIT_SPECIALIZATION(6)
COUNTDIGIT_SPECIALIZATION(7)
COUNTDIGIT_SPECIALIZATION(8)
COUNTDIGIT_SPECIALIZATION(9)
COUNTDIGIT_SPECIALIZATION(-1)
COUNTDIGIT_SPECIALIZATION(-2)
COUNTDIGIT_SPECIALIZATION(-3)
COUNTDIGIT_SPECIALIZATION(-4)
COUNTDIGIT_SPECIALIZATION(-5)
COUNTDIGIT_SPECIALIZATION(-6)
COUNTDIGIT_SPECIALIZATION(-7)
COUNTDIGIT_SPECIALIZATION(-8)
COUNTDIGIT_SPECIALIZATION(-9)

Here is an example of second version of the compile time generative recursion.

std::cout << CountDigit<1234, 1>::value << std::endl;
std::cout << CountDigit<-8, 1>::value << std::endl;
std::cout << CountDigit<-23, 1>::value << std::endl;
std::cout << CountDigit<43565, 1>::value << std::endl;
std::cout << CountDigit<123, 1>::value << std::endl;

This program still has one problem. In the above problem we came across with a problem with 19 termination conditions, but what will the situation be when our termination condition is less than 1000 or 100,000? Although we are not going to write the specialization class 100,000 times, but we still have to use the preprocessor macro 100,000 times. In other words, indirectly, we are going to introduce that much template specialization with the help of the preprocessor.

In our next attempt we are going to solve this problem by introducing one more template class and one more non type template parameter. Now we are going to introduce one more template class to check our condition, which can be even more complex than our example.

There are two main advantages of this technique; first, we are no longer using a preprocessor macro to generate lots of template specialization classes for us. And second, we can handle almost any termination condition without creating tons of new specialization classes.

template <int no>
struct IsSingleDigit
{
enum { value = (no > -10 & no < 10) ? 1 : 0 };
};
template <int no, int a, int isSingleDigit>
struct CountDigit
{
enum { value = CountDigit<no / 10, (a+1),
IsSingleDigit<no / 10>::value>::value };
};
template <int no, int a>
struct CountDigit<no, a, 1>
{
enum { value = a };
};

Here is an example of usage of third version of compile time generative recursion.

std::cout << CountDigit<1234, 1, IsSingleDigit<1234>::value>::value << std::endl;
std::cout << CountDigit<-8, 1, IsSingleDigit<-8>::value>::value << std::endl;
std::cout << CountDigit<-23, 1, IsSingleDigit<-23>::value>::value << std::endl;
std::cout << CountDigit<43565, 1, IsSingleDigit<43565>::value>::value << std::endl;
std::cout << CountDigit<123, 1, IsSingleDigit<123>::value>::value << std::endl;

In the last version of the program we just did some cosmetic changes to make it easier for the caller to call it by using default value of template parameter. We almost always passed one as a second parameter and the return value of `IsSingleDigit`

as a third parameter, therefore we use this as a default parameter in our `CountDigit`

structure.

template <int no>
struct IsSingleDigit
{
enum { value = (no > -10 && no < 10) ? 1 : 0 };
};
template <int no,
int a = 1,
int isSingleDigit = IsSingleDigit<no>::value>
struct CountDigit
{
enum { value = CountDigit<no / 10, (a+1),
IsSingleDigit<no / 10>::value>::value };
};
template <int no, int a>
struct CountDigit<no, a, 1>
{
enum { value = a };
};

Now, the usage of this structure is pretty straightforward and more readable. Here is an example of usage of the fourth version of compile time generative recursion.

std::cout << CountDigit<1234>::value << std::endl;
std::cout << CountDigit<-8>::value << std::endl;
std::cout << CountDigit<-23>::value << std::endl;
std::cout << CountDigit<43565>::value << std::endl;
std::cout << CountDigit<123>::value << std::endl;

In the last section of the first part of this article[5] we discussed template recursion with run time and compile time components of a program. We made a program to generate the simple class to make an n dimension array using template recursion. In that program and all of the compile time recursion programs we used the non-type template argument. There is one very important feature of the template meta-programming with the help of type, when instead of writing a program for one specific type, we can generalize it for any type that qualify the concept used in the program.

## 3. Linear Recursion

Linear recursion is the simplest form of recursion and perhaps the most commonly used recursion. In this recursion one function simply calls itself until it reaches the termination condition (also known as base condition); this process is known as winding. After calling the termination condition the execution of the programs returns to the caller; this is known as unwinding.

### 3.1. Structured Linear Recursion

Link list, again, perhaps the most commonly used data structure for linear recursion. We have already studied link list in previous section, this time we are going to print the elements in the link list. We can do the same thing with looping, i.e. traverse each elements of the link list until reach the element with next address equal to NULL. Here is the simple recursive implementation of printing all the elements of link list.

struct Node
{
int value;
Node* next;
};
void PrintNode(Node* pHead)
{
if (pHead != NULL)
{
PrintNode(pHead->next);
std::cout << pHead->value << std::endl;
}
else
return;
}

### 3.2. Generative Linear Recursion

If we are supposed to make a function that will create and populate a vector (or any other data structure) with some predefined data then we can solve this in either with looping or with recursion. Here is the recursive version of the function.

bool makeVector(std::vector<int>& vec, int low, int high, int increment = 1)
{
if (low > high)
return false;
if (low == high)
return true;
else
{
vec.push_back(low);
makeVector(vec, low+increment, high, increment);
}
return true;
}

In this function we are inserting the low value in the vector then incrementing it and calling it recursively until the low value becomes larger than the higher value. Here is the usage of this function.

std::vector<int> vec;
makeVector(vec, -5, 10, 2);
std::copy(vec.begin(), vec.end(), ostream_iterator<int>(std::cout, "\n"));

This might not be a good and interesting example of generative linear recursion. Let’s take a look at the variation of Josephus Problem discussed in Concrete Mathematics book[4].

“During the Jewish-Roman war, he [Josephus] was among a band of 41 Jewish rebels trapped in a cave by the Romans. Preferring suicide to capture, the rebels decided to form a circle and, proceeding around it, to kill every third remaining person until no one was left.” [4]

“In our variation, we start with n people numbered 1 to n around a circle, and we eliminate every second remaining person until only one survives” [4].

Here is the mathematical formula to solve this problem.

One more reason to select this example was that from the equation there isn’t any obvious solution for any value of n greater than 1. In other words we can’t see what would function to in case of J(n). If we take a look at this closely then these equations just show two special cases, one for even numbers and other for odd numbers in addition to termination condition. Here is the simple implementation of the Modified Josephus Problem in C++ using recursion.

int JosephusProblem(int no)
{
if (1 == no)
return 1;
if (no % 2 == 0)
return 2 * JosephusProblem(no / 2) - 1;
else
return 2 * JosephusProblem(no / 2) + 1;
}

## 4. Tail Recursion

Tail recursion is a specialized form of linear recursion where the recursive function called is usually the last call of the function. This type of recursion is usually more efficient because the smart compiler will automatically convert this recursion into loop to avoid nested function calls. Because a recursive function call is usually the last statement of a function, therefore, there isn’t any work done during the unwinding phase, instead of this they simply return the value of a recursive function call. In other words, a recursive function doesn’t store any state information, and during the unwinding phase just returns the value.

### 4.1. Structure Tail Recursion

Let’s take an example of link list again. If we want to find the maximum value in the link list we can do it with either looping or with recursion. Here is an example to find the maximum value in the link list using tail recursion.

int maxValue(Node* pHead, int MaxValue)
{
if (pHead->next == NULL)
return MaxValue;
else
return maxValue(pHead->next,
pHead->value > MaxValue ? pHead->value : MaxValue);
}

Here is the simple usage of this function

Node* pHead = NULL;
AddNode(&pHead, 15);
AddNode(&pHead, 20);
AddNode(&pHead, 65);
AddNode(&pHead, 25);
AddNode(&pHead, 55);
AddNode(&pHead, 40);
if (pHead != NULL)
{
std::cout << maxValue(pHead, pHead->value) << std::endl;
}

Note here that we check whether the link list is valid or not before calling the function, because we are passing the value of the first node of the link list as a parameter of the function.

### 4.2. Generative Tail Recursion

If we want to reverse the number again we can perform it in different ways. Here is the simple tail recursion version of it.

int reverseNumber(int n, int r = 0)
{
if (n == 0)
return r;
else
return reverseNumber(n/10, (r*10)+(n%10));
}

This function calls itself again and again recursively and passes the input parameter after dividing by 10 until it is equal to 0. At the same time this function create a reverse number and pass it as a second parameter of itself. Then during the unwinding phase just return the number as it is.

## 5. Mutual Recursion

Mutual recursion is also known as indirect recursion. In this type of recursion two or more than two functions call each other in circular way. This is the only way of doing recursion if a programming language doesn’t allow calling functions recursively. The termination condition in this recursion can be in one or all functions.

### 5.1. Structure Mutual Recursion

Let’s take a look at the problem to check that the given string is palindrome or not. The palindrome string is a string that can be the same whether read from left or right, such as “Hannah”, “Tenet”, “Civic,” and “Madam” etc. By definition, one letter word is also a palindrome, therefore this function returns true if the length of the given string is only one. This function calls another helper function named “`helperPlaindrome`

,” which was checking the first and last letter of the string and call `isPlaindrome`

again.

Here is the simple implementation of checking if string is a palindrome or not using Mutual recursion.

bool isPlaindrome(const std::string& str);
bool helperPlaindrome(const std::string& str);
bool isPlaindrome(const std::string& str)
{
if (1 == str.length())
return true;
return helperPlaindrome(str);
}
bool helperPlaindrome(const std::string& str)
{
if (str.length())
return str.at(0) == str.at(str.length() - 1)
&& isPlaindrome(str.substr(1, str.length() - 2));
else
return true;
}

### 5.2. Generative Mutual Recursion

In the previous article we have already seen two examples of mutual recursion. There are a few more interesting examples of mutual recursion defined in this paper [2]. We have already discussed the Fibonacci numbers. The actual problem of Fibonacci numbers is defined as a pair of rabbits and we are supposed to calculate the total number of rabbits after “n” months. These are the conditions defined in the problem.

During the first month there is only one pair or one rabbit and we're supposed the take one month to produce one more pair of babies while not dying. In addition, they always produce a pair of one male and one female rabbit. If we count the total number of pairs during every month then these are Fibonacci numbers.

Now instead of calculating the number of pairs every months if we want to calculate number of Adult pairs (mature paired) and number of Baby pairs then we can calculate it with the following formulae.

This is a type of mutual recursion. In this example, the “Baby” function calls the “Adult” function and vice versa. Here is the simple implementation of this problem.

int BabyPair(int no);
int AdultPair(int no);
int BabyPair(int no)
{
if (no == 1)
return 1;
else
return AdultPair(no - 1);
}
int AdultPair(int no)
{
if (no == 1)
return 0;
else
return AdultPair(no - 1) + BabyPair(no - 1);
}

## 6. Binary Recursion

In binary recursion the recursive function calls itself twice not once. This type of recursion is very useful as some data structures like traversing a tree in prefix postfix or infix order, generating Fibonacci numbers etc.

Binary recursion is a specific form of exponential recursion, where one function calls the recursive function more than once (in case of binary two). In other words, recursive functions calls exponentially in this type of recursion.

### 6.1. Structure Binary Recursion

A Binary Tree is a typical example of Binary Recursion. In a Binary tree every node has two child nodes and every child node may contain two children. Recursion is a natural choice here, because of the recursive nature of the data structure. Here is the simple code to add items in a Binary tree and display it.

struct TreeNode
{
int iData;
TreeNode* pLeft;
TreeNode* pRight;
};
void AddItem(TreeNode** pRoot, int iData)
{
if (*pRoot == NULL)
{
(*pRoot) = new TreeNode();
(*pRoot)->iData = iData;
(*pRoot)->pLeft = NULL;
(*pRoot)->pRight = NULL;
}
else
{
if (iData < (*pRoot)->iData)
AddItem(&(*pRoot)->pLeft, iData);
else if (iData > (*pRoot)->iData)
AddItem(&(*pRoot)->pRight, iData);
}
}
void PrintTree(TreeNode* pRoot)
{
if (pRoot == NULL)
return;
PrintTree(pRoot->pLeft);
std::cout << pRoot->iData << std::endl;
PrintTree(pRoot->pRight);
}

At first it looks that `AddItem`

is using Binary recursion, because it calls itself twice, but that is not a case. For any given value, the `AddItem`

function calls itself only once, either to insert items in right child or in left child. `PrintTree`

is a true Binary recursive function, because it calls itself twice for every node, to traverse both left and right children.

As we have already discussed, Binary Recursion is just a special case of Exponential Recursion, because in Exponential recursion a recursive function may call itself more than twice. Its example may be a Generalized Tree, not a Binary Tree, where any node of a Tree may contain any number of children. In real life we can see this as a directory structure of our operating system. Here is the simplest implementation of Generalized Tree.

struct GeneralizedTreeNode
{
int iData;
std::vector<GeneralizedTreeNode*> vecChildern;
};

### 6.2. Generative Binary Recursion

When we are discussing the problem subdivided into sub problems, then Binary Search would be a simplest and natural example. In Binary search we break a sorted vector into two for each comparison. Here is the simple implementation of Binary Search.

int BinarySearch(std::vector<int> vec, int first, int last, int val)
{
if (0 == vec.size())
return -1;
if (first > last)
return -1;
else
{
int mid = (first + last)/2;
if (vec.at(mid) == val)
return mid;
else if (val < vec.at(mid))
return BinarySearch(vec, first, mid-1, val);
else
return BinarySearch(vec, mid+1, last, val);
}
}

This function is similar to the `AddItem`

function of the BinaryTree. Although there are two recursive calls of `BinarySearch`

, for any given value there will be only one call that can occur. This program is not a truly Binary Recursion, because the recursive function doesn’t call itself more than once during any call.

Let’s take a look at the example of merge sort. In merge sort we subdivide our array (or vector) in two pieces and keep doing this until there is only one element left in the sub array, and then we merge all the sub arrays together. The splitting piece of this program is quite straightforward and the real fun part is in the `mergeVectors`

function. We can implement `mergeVectors`

function in two ways. Either we can create a new temporary vector and insert elements in it or we simply swap the values of existing vectors. In this program we use the second approach i.e. swap the values of existing vector rather than create a new one.

void mergeVectors(std::vector<int>::iterator iStart,
std::vector<int>::iterator iMid,
std::vector<int>::iterator iEnd)
{
for (std::vector<int>::iterator iter_ = iStart;
iter_ != iMid;
++iter_)
{
if (*iter_ > *iMid)
{
int iTemp = *iter_;
*iter_ = *iMid;
std::vector<int>::iterator iTempIter = iMid;
while (iTempIter + 1 != iEnd && *(iTempIter + 1) < iTemp)
{
std::swap(*iTempIter, *(iTempIter + 1));
++iTempIter;
}
*iTempIter = iTemp;
}
}
}
void mergeSort(std::vector<int>::iterator iStart, std::vector<int>::iterator iEnd)
{
size_t iSize = iEnd - iStart;
if (iSize <= 1)
return;
std::vector<int>::iterator iMid = iStart + (iSize / 2);
mergeSort(iStart, iMid);
mergeSort(iMid, iEnd);
mergeVectors(iStart, iMid, iEnd);
}

## 7. Nested Recursion

This is a special type of recursion when the recursive call is nested. All of the above recursion we can replace with either simple looping or a loop with stack, but this type of recursion cannot be easily replaced by a simple loop. In this type of recursion every recursive function calls another function that is also a recursive function. The nested recursive function can be the function itself or it can be another function altogether.

### 7.1. Structure Nested Recursion

Nested Link List can be a good example of Structured Nested Recursion. In a simple link list every node of the Link List simply contains data as well as address of next node. In case of nested link list every node of a link list contains two addresses. The first address is just like simple link list contains the address of next node in the link list, but the second node is an address of one more link list.

In other words, every node can contain the address of one more link list. Now the question is what might be the advantage of such a complex data structure, when we can do the same thing with two dimensional arrays? The main problem with two dimensional arrays is that every dimension should have the same length just like a Matrix. However, we can’t make a 2D array with every row containing different number of elements.

The solution of this problem is an Array of pointer, where every element of the array stores the address of another single dimensional array. It will solve our 2D array with variable number of elements in the row as shown in the figure.

But we still have two problems in it. First because it is an array it is a fixed length and if we want to increase the size of any array then I have to reallocate it in memory, copy all the elements from previous location to new location and de allocate previous memory location, which is of course a very expensive solution both in terms of time as well as memory.

Link Lists came into the picture to solve exactly the same problem. If we store that information in a Link List instead of an array then we can easily grow it dynamically without performing all the expensive steps.

Here we have two different types of Nodes. Node is the same as we studied earlier in the case of Simple Link List. `NestedNode`

has two pointers, one to store the address of the next node of the same type to create a link list of `NestedNode`

type and the other one is to store the header address of the nested link list.

Here is the simple implementation of both types of nodes in nested link list.

struct Node
{
int iData;
Node* pNextNode;
Node()
{
iData = 0;
pNextNode = NULL;
}
};
struct NestedNode
{
int iData;
Node* pHead;
NestedNode* pNextList;
NestedNode()
{
iData = 0;
pHead = NULL;
pNextList = NULL;
}
};

Here are the functions to add items in Nested Link List and Nested Link List itself.

NestedNode* AddNestedList(NestedNode* pHead, int iData)
{
if (pHead == NULL)
return NULL;
if (pHead->pNextList == NULL)
{
pHead->pNextList = new NestedNode();
pHead->iData = iData;
return pHead;
}
else
{
NestedNode* pTemp = pHead->pNextList;
while (pTemp != NULL)
{
pTemp = pTemp->pNextList;
}
pTemp = new NestedNode();
pTemp->iData = iData;
pTemp->pNextList = pHead;
pHead = pTemp;
return pHead;
}
}
void AddNestedItem(Node** pHead, int iData)
{
if (*pHead == NULL)
{
*pHead = new Node();
(*pHead)->iData = iData;
}
else
{
Node* pTemp = (*pHead)->pNextNode;
while (pTemp != NULL)
{
pTemp = pTemp->pNextNode;
}
pTemp = new Node();
pTemp->iData = iData;
pTemp->pNextNode = *pHead;
*pHead = pTemp;
}
}

Here is the usage of these functions to create a Nested Link List

NestedNode* pNested = new NestedNode();
pNested = AddNestedList(pNested, 2);
AddNestedItem(&pNested->pHead, 4);
AddNestedItem(&pNested->pHead, 14);
AddNestedItem(&pNested->pHead, 20);
AddNestedItem(&pNested->pHead, 36);
pNested = AddNestedList(pNested, 3);
AddNestedItem(&pNested->pHead, 9);
AddNestedItem(&pNested->pHead, 21);
AddNestedItem(&pNested->pHead, 27);
pNested = AddNestedList(pNested, 5);
AddNestedItem(&pNested->pHead, 25);
AddNestedItem(&pNested->pHead, 45);
AddNestedItem(&pNested->pHead, 50);
AddNestedItem(&pNested->pHead, 70);
AddNestedItem(&pNested->pHead, 85);
AddNestedItem(&pNested->pHead, 95);

And here is the function to print a Nested Link List

void PrintNestedList(Node* pHead)
{
if (pHead != NULL)
{
std::cout << " -> " << pHead->iData << std::endl;
PrintNestedList(pHead->pNextNode);
}
else
return;
}
void TraverseNode(NestedNode* pHead)
{
if (pHead == NULL)
return;
else
{
std::cout << pHead->iData << std::endl;
PrintNestedList(pHead->pHead);
TraverseNode(pHead->pNextList);
}
}

Here is the example of calling this function

TraverseNode(pNested);

### 7.2. Generative Nested Recursion

In the previous article we studied the Ackermann function as an example of a nested recursion. Here, instead of repeating the same example we are going to study one more nested recursive function named the McCarthy function also known as McCarthy 91 function.

Mathematically, the McCarthy function can be defined as

int McCarthy(int no)
{
if (no > 100)
return no - 10;
else
return McCarthy(McCarthy(no + 11));
}

## 8. References

- Modern C++ Design Generic Programming

Andrei Alexandrescu

- A Gentle Introduction to Mutual Recursion

Manuel Rubio-Sanchez, Jaime Urquiza-Fuentes, Cristobal Pareja-Flores

Proceedings of the 13th annual conference on Innovation and technology in computer science education, June 30–July 2, 2008, Madrid, Spain.

- Static Data Structure

Michael C. Burton, William G. McCulloch, Gary A. Huber

- Concrete Mathematics 2nd edition

Ronald L. Graham, Donald E Knuth, Oren Patashnik

- Recursion Primer Using C++: Part 1

Zeeshan Amjad

Recursion_Prmr_CPP_01.aspx

http://www.codeguru.com/cpp/cpp/algorithms/math/article.php/c15111/