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

  1. The factorial function

  2. An English ruler

  3. Binary search

Factorial function

Drawing an English Ruler

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

F0=0F1=1Fn=Fn−2+Fn−1  for  n>1F_0=0 \\ F_1=1 \\ F_n = F_{n-2}+F_{n-1} \; for \; n>1
c0=1c1=1c2=1+c0+c1=1+1+1=3c3=1+c1+c2=1+1+3=5c4=1+c2+c3=1+3+5=9\begin{split} c_0 = & 1 \\ c_1 = & 1 \\ c_2 = & 1+c_0+c_1=1+1+1=3 \\ c_3 = & 1+c_1+c_2=1+1+3=5 \\ c_4 = & 1+c_2+c_3=1+3+5=9 \end{split}

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?