1 - Recursion
1 - Recursion
Florenc Skuka
[email protected]
LESSON 02_B
Recursion
Page 2
Course Objectives
Page 10
Example: n! Factorial
𝑖𝑓 𝑛 ≤ 1 1
𝑛! =
𝑖𝑓 𝑛 > 1 𝑛* 𝑛 − 1 !
Example: n! Factorial
res = factorial(4);
Example: factorial(4)
res = factorial(4);
Example: factorial(4)
res = factorial(4);
Example: factorial(4)
res = factorial(4);
Example: factorial(4)
res = factorial(4);
Example: factorial(4)
res = factorial(4);
Example: factorial(4)
res = factorial(4);
Example: factorial(4)
res = 24;
Visualizing Recursion
• Example call
return 4 * 6 = 24 final answer
recursiveFactorial (1 )
call return 1
recursiveFactorial (0 )
Example: factorial(5)
Base case example - 2
Display an array
◼ Show the last element. Then call the function to show the previous element in
the list.
◼ What is the base case?
if(n==0)
◼ What we do in the base case?
Show just the number and don’t recur
System.out.print(lst[N]+", ");
◼ Any other case:
System.out.print(lst[N]+", ");
Ibrahim
show(lst,N-1);
Mesecan
Page 23
Display an array
𝑛= 0 𝑙𝑠𝑡[𝑛]
◼ 𝐹𝑀𝑖𝑛(𝑙𝑠𝑡, 𝑛) =
𝑛≥ 1 min(𝑙𝑠𝑡 𝑛 , 𝐹𝑀𝑖𝑛(𝑙𝑠𝑡, 𝑛 − 1)
FindMin
𝑛= 0 𝑙𝑠𝑡[𝑛]
◼ 𝐹𝑀𝑖𝑛(𝑙𝑠𝑡, 𝑛) =
𝑛≥ 1 min(𝑙𝑠𝑡 𝑛 , 𝐹𝑀𝑖𝑛(𝑙𝑠𝑡, 𝑛 − 1)
return f( 2 ) + f( 1 )
return f( 1 ) + f( 0 ) return 1
return 1 return 0
Fibonacci
static int cnt = 1;
static int Fib( int N )
{
cnt++;
if( N <= 1 ) return 1;
return Fib(N - 1) + Fib( N - 2 );
}
Recursion:
◼ Terminates when a base case is reached.
◼ Each recursive call requires extra space on the stack frame
(memory).
◼ If we get infinite recursion, the program may run out of
memory and result in stack overflow.
◼ Solutions to some problems are easier to formulate
recursively.
Recursion versus Iteration
Iteration:
◼ Terminates when a condition is proven to be false.
◼ Each iteration does not require any extra space.
◼ An infinite loop could loop forever since there is no extra
memory being created.
◼ Iterative solutions to a problem may not always be as
obvious as a recursive solution.
Recursive or Iterative