Recursion
Definition
Recursion is a technique by which a function makes one or more calls to itself during execution, or by which a data structure relies upon smaller instances of the very same type of structure in its representation.
Example
The representative examples are below
The factorial function
An English ruler
Binary search
Factorial function

Drawing an English Ruler


Binary Search
Binary Search is the method that used to efficiently locate a target value within a sorted sequence of n elements.(If it is not sorted, we use a sequential search algorithm.)
If the target equals data[mid], then we have found the item we are looking for, and the search terminates successfully.
If target < data[mid], then we recur on the first half of the sequence, that is, on the interval of indices from low to mid-1.
If target > data[mid], then we recur on the second half of the sequence, that is, on the interval of indices from mid+1 to high.


Recursion Run Amok
Fibonacci Numbers
exponential in n.
Linear recursion
0 1 1 2
We don't have to use a recursive function twice. Instead of using twice, we just let the return value have pair structure. By doing this, the time complexity is reduced from exponential form to linear form.
Exercises
Linear recursion can be a useful tool for processing a data sequence, such as a Python list.
Q1. Let's compute the sum of a sequence S, of n integers.
S=[4,3,6,2,8], linear_sum(S,5)=23
Q2. Write a short recursive Python function that finds the minimum and maximum values in a sequence without using any loops.
Q3. Give a recursive algorithm to compute the product of two positive integers, m and n, using only addition and subtraction.
Last updated
Was this helpful?