Docsity

Recursion: Understanding Functions that Call Themselves, Study notes of Data Structures and Algorithms

Partial preview of the text

Download Recursion: Understanding Functions that Call Themselves and more Study notes Data Structures and Algorithms in PDF only on Docsity!

Recursion

Ken Nguyen Fall, 2003

Basic Recursion

Rooted in mathematics, holds true for positivenumbers n - A lot of formulas are recursive - Correctness is proved by induction - Induction Proof: - => Basis: true for very simple case - => Inductive hypothesis: Assume to be true forany positive number k - => Prove it be true for k+

What is Recursive Function?

  • A recursive function is a function directly or indirectly makes a call to itself - A valid recursive function requires: => base case: Always has at least one case that can be solved w/o using recursion => Make progress: Any recursive call must make progress toward a base case.

Examples

  • Print a number, e.g. 123456 • Perform sum of the first n numbers (n>=1) • Perform x^y • Perform n!, i.e. F = n* (n-1)!, 0! = 1 • Fibonacci, i.e. F i^

=F

i-

+ F

i-

, F

0

=0, F

1

  • Expression trees and Tree processing.
  • Recursive function must terminate • Recursion is achieved by using stack (activation records) - Recursion can always be replaced by iterative codes (loops) - Try not to over used recursion • Never duplicate work by solving the same instance of a problem in separaterecursive calls.

Disadvantage

  • Recursions use more memory • In general recursive codes run slower than iterative codes

Summary

  • Recursion • Proof by induction • Iterative v.s. recursive • Complexity of recursive problems