Академический Документы
Профессиональный Документы
Культура Документы
A recursive function is simply a function that repeatedly calls itself and the trick is to
realize when to stop calling ourselves to avoid infinite loops that result in stack overflows.
2 [1, 2, 3]
3 [1, 3, 2]
4 [2, 1, 3]
5 [2, 3, 1]
6 [3, 1, 2]
7 [3, 2, 1]
Ans If the base case is not reached or not defined, then the stack overflow problem may arise.
4 Given a linked list, write a function that prints the nodes of the list in reverse order.
1,2,3
Ans
printReversedList(1 -> 2 -> 3)
3
eg.
2
1
5 When should you use recursion?
We can use recursion to do anything that you can do with non-recursive code. There are a
lot of cases where writing a function recursively will be a lot more effort and may run less
efficiently than the comparable iterative code.
6 Is it easier to solve it recursively than iteratively?
Any problem can be solved either recursively or iteratively, so you just have to decide
which is easier.
7 What’s the base case?
The base case is when we reach an input for which we know what the output would be.”
The base case is thus the condition which terminates recursion.
In the example here, the base case is when the input has nothing for us to loop through. It
could be because the input is nil (or an empty hash). When that happens, we know the
output is {books: 0, movies: 0, articles: 0}.
{
if(x == 0)
return y;
else
return fun1(x - 1, x + y);
}
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.
{
if(start_index >= end_index)
return;
int min_index;
int temp;
/* Assume that 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);
}
Answer: The function fun2() is a recursive implementation of Selection Sort.
Output: 100
fun() returns the maximum value in the input array a[] of size n.
19 Predict the output of following program. What does the following fun() do in general?
Output: 91
fun(99) = fun(fun(110)) since 99 ? 100
= fun(100) since 110 > 100
= fun(fun(111)) since 100 ? 100
= fun(101) since 111 > 100
= 91 since 101 > 100
Returned value of fun() is 91 for all integer rguments n 101. This function is known
as McCarthy 91 function.
In the recursive program, the solution to the base case is provided and the solution of the
bigger problem is expressed in terms of smaller problems.