Can every recursion be changed to iteration?

后端 未结 5 711
遇见更好的自我
遇见更好的自我 2021-01-13 19:14

Is every recursive function convertible to iteration? What characteristic should a recursive function have in order for it to be implemented using iteration?

<
5条回答
  •  独厮守ぢ
    2021-01-13 20:06

    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.

提交回复
热议问题