Recursion


recursion =

In programming languages, recursion happens when a method calls itself

 

 

 

Rules of recursion

1)

 

2)

 


Example: binary search

Algorithm: binarySearch(dictionary, word)

 

 

 

 

 

 

 

 

Example: choosing k out of n things

How many ways are there to choose k out of n items (e.g., 3 out of 5 items)?

 

 

 

 

 

 

 

 

 

 

 

 

 

 

 

 

Example:

Write a recursive method that determines if a string represents a non-negative integer. Assume '+' has been stripped off (if necessary).

 

A string is a non-negative integer if

 

 

 

 

 

 

 

 

 

 

 

 

Example:

Write a recursive method that determines if a chain of linked nodes containing integers is strictly increasing.

 

 

 

 

 

 

 

 

 

 

 

 

 

 

 

 

 

 

 

 

 

 

Example: palindromes

Write a recursive method that determines if string is a palindrome.

Examples of palindromes:

Assume: input string is not null, has been stripped of all spaces and punctuation, and is in all lower-case

Useful string methods:

 

 

 

 

 

 

 

 

 

 

 

 


Challenge:

Write a recursive method that counts the number of even values in a chain of linked nodes containing integer values.

First complete the English description for the base cases and recursive case:

Then complete the recursive countEven method:

public static int countEven(Listnode<Integer> head) {

Analyzing complexity for recursive methods

Two options:

1)

2)

Using recurrence relations

Step 1: write recurrence relations

T(0) = _____

T(N) = _____ + _____ × T( _____ )

Step 2: guess a solution

Step 3: verify solution

Step 4: apply big-O notation to guessed solution


Analyzing recursive method: strictlyIncreasing

 

 

 

 

 

 

 

 

 

 

 

 

 

 

Analyzing recursive method: isPalindrome

 

 

 

 

 

 

 

 

 

 

 

 

 

 

Challenge: analyze the complexity of countEven using recurrence relations


Example: the Towers of Hanoi