Practice Questions for Recursion | Set 1

Explain the functionality of following functions.

Question 1

filter_none

edit
close

play_arrow

link
brightness_4
code

int fun1(int x, int y) 
{
  if(x == 0)
    return y;
  else
    return fun1(x - 1,  x + y);
}

chevron_right


Answer: The function fun() calculates and returns ((1 + 2 … + x-1 + x) +y) which is x(x+1)/2 + y. For example if x is 5 and y is 2, then fun should return 15 + 2 = 17.



Question 2

filter_none

edit
close

play_arrow

link
brightness_4
code

//minimum index finder
int minIndex(int arr[], int s, int e)
{
    int sml = INT32_MAX;
    int mindex;
    for (int i = s; i < e; i++)
    {
        if (sml > arr[i])
        {
            sml = arr[i];
            mindex = i;
        }
    }
    return mindex;
}
  
void fun2(int arr[], int start_index, int end_index)
{
  if(start_index >= end_index)   
     return;
  int min_index; 
  int temp; 
  
  /*minIndex() returns index of minimum value in 
    array arr[start_index...end_index] */
  min_index = minIndex(arr, start_index, end_index);
  
  temp = arr[start_index];
  arr[start_index] = arr[min_index];
  arr[min_index] = temp;        
  
  fun2(arr, start_index + 1, end_index);
}     

chevron_right


Answer: The function fun2() is a recursive implementation of Selection Sort.

Please write comments if you find any of the answers/codes incorrect, or you want to share more information about the topics discussed above.

Don’t stop now and take your learning to the next level. Learn all the important concepts of Data Structures and Algorithms with the help of the most trusted course: DSA Self Paced. Become industry ready at a student-friendly price.




My Personal Notes arrow_drop_up

Improved By : NikSta

Article Tags :
Practice Tags :


19


Please write to us at contribute@geeksforgeeks.org to report any issue with the above content.