DSP n
DSP n
RECURSION
Syllabus
Recursion, Properties of Recursion, Recursive functions: Factorials, Recursive Call stack, The Fibonacci
Sequence, How Recursion Works- The Run Time Stack, Recursive Applications- Recursive Binary Search,
Towers of Hanoi.
Recursion
A function (or method) can call any other function (or method), including itself.
A function that calls itself is known as a recursive function.
Recursion is a technique that solves a problem by solving a smaller
problem of the same type.
Types of Recursion
1. Direct Recursion
2. Indirect Recursion
Direct Recursion
The function calls itself repeatedly until a base condition is solved.
Example
def function( )
//…….
function body
……..//
function( ) ---------------Recursive call
Indirect Recursion
The function calls another function which in turn calls the first function.
Example
def function1( )
//…….
function body
……..//
function2( )
def function2( )
//…….
function body
……..//
function1( )
Base Case
A recursive function definition has one or more base cases (stopping condition), meaning input(s)
for which the function has a ready result without further recurring.
Because the base case breaks the chain of recursion, it is sometimes also called the "terminating
case".
For example, for a factorial function the base case can be defined as, factorial (0) = factorial (1) = 1.
Advantages of Recursion
Terminates when a base case is reached Terminate when a defined condition is met.
Each recursive call requires space in memory Each iteration is not stored in memory
An infinite recursion results in stack overflow An infinite iteration will run while hardware is
error. powered.
Some problems are naturally better suited to Iterative solutions may not always be obvious.
recursive solutions
Properties of a Recursion
All recursive solutions must satisfy three rules or properties:
1. A recursive solution must contain a base case.
2. A recursive solution must contain a recursive case.
3. A recursive solution must make progress toward the base case.
A recursive solution subdivides a problem into smaller versions of itself.
For a problem to be subdivided, it typically must consist of a data set or a term that can be divided
into smaller sets or a smaller term.
This subdivision is handled by the recursive case when the function calls itself.
The base case is the terminating case and represents the smallest subdivision of the problem.
It signals the end of the virtual loop or recursive calls.
Finally, a recursive solution must make progress toward the base case or the recursion will never
stop resulting in an infinite virtual loop.
This progression typically occurs in each recursive call when the larger problem is divided into
smaller parts.
Recursive Functions:Factorials
The factorial of a positive integer n can be used to calculate the number of permutations of n elements. The
n! = n ∗ (n − 1) ∗(n − 2) ∗ . . . 1
function is defined as:
1! = 1 ∗ (1 − 1)!
0! = 1
2! = 2 ∗ (2 − 1)!
3! = 3 ∗ (3 − 1)!
4! = 4 ∗ (4 − 1)!
5! = 5 ∗ (5 − 1)!
Since the function is defined in terms of itself and contains a base case, a Recursive definition can be
Code:
def fib(n):
if (n == 0):
return 0
if n == 1 or n == 2:
return 1
else:
return fib(n - 1) + fib(n - 2)
n = int(input("Enter a number"))
print("Fibonacci series of %d numbers are :" % n, end=" ")
for i in range(0, n):
OUTPUT
Enter a number 5
Fibonacci series of 5 numbers are : 0 1 1 2 3
Recursive Applications
Recursive Binary Search
Binary Search implies continually dividing the searching interval into 2 equal parts to discover an
element in a sorted array, and recurrent binary Search entails breaking down the complete binary
search procedure into smaller issues.
A recursive binary search is the recursion answer to a binary search.
The following are the characteristics that all-recursive solutions must meet:
a. A base case is required for a recursive approach.
b. There must be a recursive test case in a recursive approach.
c. A recursive approach has to get nearer to the base case.
The lowest subdivision of a complicated problem is represented by a base case, which is a final
case.
So, to perform the binary Search by recursive method, our algorithm must contain a base case and a
recursive case, with the recursive case progressing to the base case.
Else the process would never finish and result in an endless loop.
The binary search technique reduces the time it takes to find a specific element inside a sorted
array.
The binary search method is often implemented iteratively, but we may also implement it
recursively by breaking it down into smaller pieces.
Code:
def binary_search(array, low, high, x):
if high >= low:
mid = (high + low) / 2
if array[mid] == x:
return mid
elif array[mid] > x:
return binary_search(array, low, mid - 1, x)
else:
return binary_search(array, mid + 1, high, x)
else:
return -1
array = [ 2, 4, 6, 8, 20, 40, 60, 80]
x=6
result = binary_search(array, 0, len(array)-1, x)
if result != -1:
print("The index of the Element is", str(result))
else:
print("This element is not present in your Array.")
Tower of Honoi
This is a toy problem that is easily solved recursively. There are three towers (posts) A, B and C. Initially,
there are n disks of varying sizes stacked on tower A, ordered by their size, with the largest disk in the
bottom and the smallest one on top. The object of the game is to have all n discs stacked on tower B in the
same order, with the largest one in the bottom. The third tower is used for temporary storage.