Saturday, August 1, 2020

Program Execution (control flow) in a double recursive call


If a function calls itself twice recursively, its tracing tree (program execution/control flow) will be a binary tree




//Understanding double recursion part 1
#include<stdio.h>
//Global variable
int level = 0;
/*
split a list in two equal halves recursively,
and print the level of the binary tree for each node(function call) value pair.

This is the same function used in the DIVIDE & CONQUER technique (splitting
a list from mid recursive ) of  Merge Sort.
*/
void split(int low, int high)
{
    level++; //increment the level each step downwards journey of program execution
    int mid;
    //printf("low = %d High = %d Level = %d\n",low,high,level);
    printf("%d %d Level = %d\n",low,high,level);
    if(low<high)
    {
        mid = (low + high)/2;
        split(low,mid);               //split the left half recursively
        split(mid + 1,high);       //split the right half recursively
    }
    level--; //decrement level as retrace each step upwards the tree, of program execution.
}
int main(void)
{
    printf("For input 1 and 8\n"); // A list of 8 elements, index starting from 1
    split(1,8);
    printf("For input 1 and 16\n"); // A list of 16 elements, index starting from 1
    split(1,16);
    return 0;
}

Output:




/*
Understanding double recursion part 2
Making both the recursive calls in the
SAME line (return statement) also produces
the same result.
The only difference now is that you need to pass
the level as the third argument to the function.
*/
#include<stdio.h>
//Global variable
int level = 0;
/*
split a list in two equal halves recursively,
and print the level of the binary tree for each node(function call) value pair.
*/
int split(int low, int high, int height)
{
    height++; //increment the level each step down
    int mid;
    printf("%d %d Level = %d\n",low,high,height);
    //base condition
    if(low == high)
    {
        return 1;
    }
    if(low<high)
    {
        mid = (low + high)/2;
        return split(low,mid,height) + split(mid + 1,high,height);// The recursive calls in the SAME line
    }
    height--; //decrement level as retrace each step upward
}
int main(void)
{
    printf("For input 1 and 8\n");
    printf("%d \n",split(1,8,level));
    printf("For input 1 and 16\n");
    printf("%d \n",split(1,16,level));
    return 0;
}

Ouput:


No comments:

Post a Comment

How can I run a C++ program directly from Windows?

How-can-I-run-a-C-program-directly-from-Windows