Objectives

  • Define Recursion
     
  • Define and identify "base cases"
     
  • Define and identify a "recursive step"
     
  • Write a recursive function

Recursion Is

"an equation that recursively defines a sequence or multidimensional array of values, once one or more initial terms are given: each further term of the sequence or array is defined as a function of the preceding terms."

Mathematically

wtf does that mean?

Recursion Is

A function which calls itself.

function recursive() {
    
    // Boom goes the call stack
    recursive();
}

Lets Run This Code...

Recursion Is

Analogous To

Recursion Is

"the repeated application of a recursive procedure or definition."

 

For example: A recursive definition.

 

Recursively

Why its Useful

It turns out that many problems can be solved by applying the same logic on a subset of the original problem.

 

As we get into lists, trees, and graphs recursive logic will become increasingly valuable.

Example: Fibonacci  Sequence

Fib(0) = 1

Fib(1) = 1

Fib(n) = Fib(n-1) + Fib(n-2)

This is a complete definition of the Fibonacci sequence:

Example: Fibonacci  Sequence

Fib(0) = 1

Fib(1) = 1

Fib(n) = Fib(n-1) + Fib(n-2)

These two are called "base cases" and prevent us from recursing infinitely:

Example: Fibonacci  Sequence

Fib(0) = 1

Fib(1) = 1

Fib(n) = Fib(n-1) + Fib(n-2)

This is called the "recursive step" which computes the sub-solutions.

Example: Fibonacci  Sequence

Fib(5)

 

Fib(4) + Fib(3)

Fib(3) + Fib(2)     Fib(2) + Fib(1)

Fib(2) + Fib(1)   Fib(0) + Fib(1)   Fib(0) + Fib(1)

Fib(0) + Fib(1)

Example: Fibonacci  Sequence

function fib(n) {
    // First we're going to do the base cases
    if(n < 0) {
        throw new Error("invalid input, negative n);
    }
    if(n === 0 || n === 1) {
        return 1
    }
}

Example: Fibonacci  Sequence

function fib(n) {
    // First we're going to do the base cases
    if(n < 0) {
        throw new Error("invalid input, negative n);
    }
    if(n === 0 || n === 1) {
        return 1
    }

    // If it wasn't a base-case, apply the recursive step
    return fib(n-2) + fib(n-1);
}

Planning Recursion

Always start with the base cases.

In Fibonacci that was n === 1 or n === 0

 

Next, think about the recursive step as getting your algorithm one step closer to a base-case

 

In Fibonacci, that was decrementing n before calling fib again.

Example: Binary Search

Find the position of 3 in this list:

 

[0,1,1,2,3,4,5,6,12,90]

->

[0,1,1,2,3]

->

[2,3]

->

Found it.

Example: Binary Search

Lets think about how we *might* code binary search recursively.

Questions?

Complete the exercises found here:

 

https://github.com/gSchool/recursion-practice

 

 

Recursion

By Tyler Bettilyon

Recursion

  • 1,368