Is every recursive function convertible to iteration? What characteristic should a recursive function have in order for it to be implemented using iteration?
<
If you have a simple "tail" recursion, then you can use a loop instead (e.g. factorial function). In more complex functions, you have to use a stack
structure and a while (!stack.empty())
loop. However, if you have quite complex recursion, such as Towers of Hanoi
, Merge Sort
, and printing truth table
, you will have to use a stack
with while
loop, as previous, but with a switch
statement to determine the current status of call.
Recursive:
void mergeSort(int start, int end)
{
if (start < end)
{
mergeSort(start, (start + end) / 2);
mergeSort((start + end) / 2 + 1, end);
Merge(start, end);
}
}
Iterative:
void mergeSort()
{
stack st;
st.push(1);
int status;
while (!st.empty())
{
status = st.pop();
switch (status)
{
case 1:
....
break;
case 2:
break;
}
}
}
I highly recommend this excellent pdf which explains the process in detail.