RECURSION Lecture 6 CS2110 – Fall 2009. 2 3 Recursion Overview 4  Recursion is a powerful technique for specifying functions, sets, and programs 

Slides:



Advertisements
Similar presentations
Introduction to Recursion and Recursive Algorithms
Advertisements

Recursion –a programming strategy for solving large problems –Think “divide and conquer” –Solve large problem by splitting into smaller problems of same.
1 Dynamic Programming Jose Rolim University of Geneva.
© Janice Regan, CMPT 102, Sept CMPT 102 Introduction to Scientific Computer Programming Recursion.
Recursion. Binary search example postponed to end of lecture.
Unit 181 Recursion Definition Recursive Methods Example 1 How does Recursion work? Example 2 Problems with Recursion Infinite Recursion Exercises.
CS 536 Spring Code generation I Lecture 20.
Chapter 10 Recursion. Copyright © 2005 Pearson Addison-Wesley. All rights reserved Chapter Objectives Explain the underlying concepts of recursion.
Recursion.
28/06/2015CMPUT Functions (2)  Function calling convention  Various conventions available  One is specified by CMPUT229  Recursive functions.
Digression: the “Stack” 1 CS502 Spring 2006 Digression: the “Stack” Imagine the following program:– int factorial(int n){ if (n
Code Generation CS 480. Can be complex To do a good job of teaching about code generation I could easily spend ten weeks But, don’t have ten weeks, so.
Dynamic Programming Introduction to Algorithms Dynamic Programming CSE 680 Prof. Roger Crawfis.
RECURSION Lecture 7 CS2110 – Spring Overview references to sections in text 2  Note: We’ve covered everything in JavaSummary.pptx!  What is recursion?
Discrete Mathematics Algorithms. Introduction  An algorithm is a finite set of instructions with the following characteristics:  Precision: steps are.
Stacks & Recursion. Stack pushpop LIFO list - only top element is visible top.
1 Storage Classes, Scope, and Recursion Lecture 6.
RECURSION Lecture 6 CS2110 – Fall Overview references to sections in text 2  Note: We’ve covered everything in JavaSummary.pptx!  What is recursion?
Recursion l Powerful Tool l Useful in simplifying a problem (hides details of a problem) l The ability of a function to call itself l A recursive call.
Chapter 9: Recursion1 CHAPTER 9 RECURSION. Recursion  Concept of recursion  A recursive: Benefit and Cost  Comparison : Iterative and recursive functions.
RECURSION Lecture 7 CS2110 – Fall Overview references to sections in text 2  Note: We’ve covered everything in JavaSummary.pptx!  What is recursion?
Week 5 - Monday.  What did we talk about last time?  Linked list implementations  Stacks  Queues.
Stephen P. Carl - CS 2421 Recursion Reading : Chapter 4.
Data Structures and Algorithms Stacks. Stacks are a special form of collection with LIFO semantics Two methods int push( Stack s, void *item ); - add.
Computer Science Department Data Structure & Algorithms Lecture 8 Recursion.
ICS220 – Data Structures and Algorithms Dr. Ken Cosh Week 5.
Review Introduction to Searching External and Internal Searching Types of Searching Linear or sequential search Binary Search Algorithms for Linear Search.
Chapter 8 Recursion Modified.
Chapter 4 Recursion. Copyright © 2004 Pearson Addison-Wesley. All rights reserved.1-2 Chapter Objectives Explain the underlying concepts of recursion.
Recursion. What is recursion? Rules of recursion Mathematical induction The Fibonacci sequence Summary Outline.
Recursion, pt. 1 The Foundations. What is Recursion? Recursion is the idea of solving a problem in terms of itself. – For some problems, it may not possible.
RECURSION Lecture 6 CS2110 – Fall Overview references to sections in text 2  Note: We’ve covered everything in JavaSummary.pptx!  What is recursion?
CSC 221: Recursion. Recursion: Definition Function that solves a problem by relying on itself to compute the correct solution for a smaller version of.
Data Structures R e c u r s i o n. Recursive Thinking Recursion is a problem-solving approach that can be used to generate simple solutions to certain.
Recursion Unit 15. Recursion: Recursion is defined as the process of a subprogram calling itself as part of the solution to a problem. It is a problem.
© 2011 Pearson Education, publishing as Addison-Wesley Chapter 8: Recursion Presentation slides for Java Software Solutions for AP* Computer Science 3rd.
1/32 This Lecture Substitution model An example using the substitution model Designing recursive procedures Designing iterative procedures Proving that.
1 Lecture 3 Part 2 Storage Classes, Scope, and Recursion.
© Janice Regan, CMPT 128, February CMPT 128: Introduction to Computing Science for Engineering Students Recursion.
RECURSION Lecture 6 CS2110 – Spring Recursion 2  Arises in three forms in computer science  Recursion as a mathematical tool for defining a function.
7. RECURSIONS Rocky K. C. Chang October 12, 2015.
1 Recursion. 2 A process by which a function calls itself repeatedly  Either directly. X calls X  Or cyclically in a chain. X calls Y, and Y calls X.
1 Recursion Recursive function: a function that calls itself (directly or indirectly). Recursion is often a good alternative to iteration (loops). Its.
Recursion by Ender Ozcan. Recursion in computing Recursion in computer programming defines a function in terms of itself. Recursion in computer programming.
Chapter 6 (Lafore’s Book) Recursion Hwajung Lee.  Definition: An algorithmic technique. To solve a problem on an instance of size n, the instance is:
CSC 143 P 1 CSC 143 Recursion [Chapter 5]. CSC 143 P 2 Recursion  A recursive definition is one which is defined in terms of itself  Example:  Compound.
RECURSION (CONTINUED) Lecture 9 CS2110 – Spring 2016.
Recursion.
CS314 – Section 5 Recitation 9
Recursion.
Lecture 12.
Functions.
MSc/ICY Software Workshop , Semester 2
Data Structures and Algorithms
Abdulmotaleb El Saddik University of Ottawa
Recursion (Continued)
Stacks Chapter 4.
Recursive Thinking Chapter 9 introduces the technique of recursive programming. As you have seen, recursive programming involves spotting smaller occurrences.
Chapter 8: Recursion Java Software Solutions
Recursive Thinking Chapter 9 introduces the technique of recursive programming. As you have seen, recursive programming involves spotting smaller occurrences.
Recursion "To understand recursion, one must first understand recursion." -Stephen Hawking.
Stacks & Recursion.
Chapter 8: Recursion Java Software Solutions
CS201: Data Structures and Discrete Mathematics I
Unit 3 Test: Friday.
Stack Frames and Functions
Module 1-10: Recursion.
Chapter 8: Recursion Java Software Solutions
Where is all the knowledge we lost with information? T. S. Eliot
Presentation transcript:

RECURSION Lecture 6 CS2110 – Fall 2009

2

3

Recursion Overview 4  Recursion is a powerful technique for specifying functions, sets, and programs  Example recursively-defined functions and programs  factorial  combinations  exponentiation (raising to an integer power)  Example recursively-defined sets  grammars  expressions  data structures (lists, trees,...)

The Factorial Function (n!) 5  Define n! = n·(n  1)·(n  2)···3·2·1 read: “n factorial”  E.g., 3! = 3·2·1 = 6  By convention, 0! = 1  The function int  int that gives n! on input n is called the factorial function 

The Factorial Function (n!) 6  n! is the number of permutations of n distinct objects  There is just one permutation of one object. 1! = 1  There are two permutations of two objects: 2! =  There are six permutations of three objects: 3! =  If n > 0, n! = n·(n  1)!

Permutations of 7  Total number = 4·3! = 4·6 = 24: 4! Permutations of non-orange blocks Each permutation of the three non- orange blocks gives four permutations when the orange block is included

Observation 8  One way to think about the task of permuting the four colored blocks was to start by computing all permutations of three blocks, then finding all ways to add a fourth block  And this “explains” why the number of permutations turns out to be 4!  Can generalize to prove that the number of permutations of n blocks is n!

A Recursive Program 9 static int fact(int n) { if (n = = 0) return 1; else return n*fact(n-1); } 0! = 1 n! = n·(n  1)!, n > Execution of fact(4) fact(1) fact(4) fact(3) fact(0) fact(2) 24

General Approach to Writing Recursive Functions Try to find a parameter, say n, such that the solution for n can be obtained by combining solutions to the same problem using smaller values of n (e.g., (n-1) in our factorial example) 2. Find base case(s) – small values of n for which you can just write down the solution (e.g., 0! = 1) 3. Verify that, for any valid value of n, applying the reduction of step 1 repeatedly will ultimately hit one of the base cases

A cautionary note 11  Keep in mind that each instance of your recursive function has its own local variables  Also, remember that “higher” instances are waiting while “lower” instances run  Not such a good idea to touch global variables from within recursive functions  Legal… but a common source of errors  Must have a really clear mental picture of how recursion is performed to get this right!

The Fibonacci Function 12  Mathematical definition: fib(0) = 0 fib(1) = 1 fib(n) = fib(n  1) + fib(n  2), n ≥ 2  Fibonacci sequence: 0, 1, 1, 2, 3, 5, 8, 13, … static int fib(int n) { if (n == 0) return 0; else if (n == 1) return 1; else return fib(n-1) + fib(n-2); } two base cases! Fibonacci (Leonardo Pisano) 1170  1240? Statue in Pisa, Italy Giovanni Paganucci 1863

Recursive Execution 13 static int fib(int n) { if (n == 0) return 0; else if (n == 1) return 1; else return fib(n-1) + fib(n-2); } fib(4) fib(3)fib(2) fib(1) fib(0) fib(2)fib(1) fib(0) Execution of fib(4):

One thing to notice 14  This way of computing the Fibonacci function is elegant, but inefficient  It “recomputes” answers again and again!  To improve speed, need to save known answers in a table!  Called a cache fib(4) fib(3)fib(2) fib(1) fib(0) fib(2)fib(1) fib(0)

Adding caching to our solution  Before:  After 15 static int fib(int n) { if (n == 0) return 0; else if (n == 1) return 1; else return fib(n-1) + fib(n-2); } ArrayList known = new ArrayList ; ArrayList cached = new ArrayList ; static int fib(int n) { int v; if(known[n]) return cached[n]; if (n == 0) v = 0; else if (n == 1) v = 1; else v = fib(n-1) + fib(n-2); known[n] = true; cached[n] = v; return v; }

Notice the development process 16  We started with the idea of recursion  Created a very simple recursive procedure  Noticed it will be slow, because it wastefully recomputes the same thing again and again  So made it a bit more complex but gained a lot of speed in doing so  This is a common software engineering pattern

Combinations (a.k.a. Binomial Coefficients) 17  How many ways can you choose r items from a set of n distinct elements? ( ) “n choose r” ( ) = number of 2-element subsets of {A,B,C,D,E} 2-element subsets containing A: {A,B}, {A,C}, {A,D}, {A,E} 2-element subsets not containing A: {B,C},{B,D},{B,E},{C,D},{C,E},{D,E}  Therefore, = +  … in perfect form to write a recursive function! ( ) nrnr 5252

Combinations 18 = +, n > r > 0 = 1 ( ) nrnr n1rn1r n1r1n1r1 nnnn n0n = Pascal’s triangle Can also show that = ( ) nrnr n! r!(n  r)!

Binomial Coefficients 19 (x + y) n = x n + x n  1 y + x n  2 y 2 + ··· + y n =  x n  i y i ( ) nini nnnn n0n0 n1n1 n2n2 n i = 0 Combinations are also called binomial coefficients because they appear as coefficients in the expansion of the binomial power (x+y) n :

Combinations Have Two Base Cases 20  Coming up with right base cases can be tricky!  General idea:  Determine argument values for which recursive case does not apply  Introduce a base case for each one of these Two base cases = +, n > r > 0 = 1 ( ) nrnr n1rn1r n1r1n1r1 nnnn n0n0

Recursive Program for Combinations 21 static int combs(int n, int r) { //assume n>=r>=0 if (r == 0 || r == n) return 1; //base cases else return combs(n-1,r) + combs(n-1,r-1); } = +, n > r > 0 = 1 ( ) nrnr n1rn1r n1r1n1r1 nnnn n0n0

Exercise for the reader (you!) 22  Modify our recursive program so that it caches results  Same idea as for our caching version of the fibonacci series  Question to ponder: When is it worthwhile to adding caching to a recursive function?  Certainly not always…  Must think about tradeoffs: space to maintain the cached results vs speedup obtained by having them

Positive Integer Powers 23  a n = a·a·a···a (n times)  Alternate description:  a 0 = 1  a n+1 = a·a n static int power(int a, int n) { if (n == 0) return 1; else return a*power(a,n-1); }

A Smarter Version 24  Power computation:  a 0 = 1  If n is nonzero and even, a n = (a n/2 ) 2  If n is odd, a n = a·(a n/2 ) 2 Java note: If x and y are integers, “x/y” returns the integer part of the quotient  Example: a 5 = a·(a 5/2 ) 2 = a·(a 2 ) 2 = a·((a 2/2 ) 2 ) 2 = a·(a 2 ) 2 Note: this requires 3 multiplications rather than 5!  What if n were larger?  Savings would be more significant  This is much faster than the straightforward computation  Straightforward computation: n multiplications  Smarter computation: log(n) multiplications

Smarter Version in Java 25  n = 0: a 0 = 1  n nonzero and even: a n = (a n/2 ) 2  n nonzero and odd: a n = a·(a n/2 ) 2 static int power(int a, int n) { if (n == 0) return 1; int halfPower = power(a,n/2); if (n%2 == 0) return halfPower*halfPower; return halfPower*halfPower*a; } parameters local variable  The method has two parameters and a local variable  Why aren’t these overwritten on recursive calls?

Implementation of Recursive Methods 26  Key idea:  Use a stack to remember parameters and local variables across recursive calls  Each method invocation gets its own stack frame  A stack frame contains storage for  Local variables of method  Parameters of method  Return info (return address and return value)  Perhaps other bookkeeping info

Stacks 27  Like a stack of dinner plates  You can push data on top or pop data off the top in a LIFO (last-in- first-out) fashion  A queue is similar, except it is FIFO (first-in-first-out) top element 2nd element 3rd element... bottom element... top-of-stack pointer stack grows

Stack Frame 28  A new stack frame is pushed with each recursive call  The stack frame is popped when the method returns  Leaving a return value (if there is one) on top of the stack a stack frame return info local variables parameters

Example: power(2, 5) 29 return info (a = ) 2 (n = ) 5 (hP = ) ? return info (a = ) 2 (n = ) 5 (hP = ) ? return info (a = ) 2 (n = ) 2 (hP = ) ? return info (a = ) 2 (n = ) 5 (hP = ) ? return info (a = ) 2 (n = ) 2 (hP = ) ? return info (a = ) 2 (n = ) 1 (hP = ) ? return info (a = ) 2 (n = ) 5 (hP = ) 4 return info (a = ) 2 (n = ) 5 (hP = ) ? return info (a = ) 2 (n = ) 2 (hP = ) 2 return info (a = ) 2 (n = ) 5 (hP = ) ? return info (a = ) 2 (n = ) 2 (hP = ) ? return info (a = ) 2 (n = ) 1 (hP = ) 1 (retval = ) 1 (retval = ) 2 (retval = ) 4 (retval = ) 32

How Do We Keep Track? 30  At any point in execution, many invocations of power may be in existence  Many stack frames (all for power) may be in Stack  Thus there may be several different versions of the variables a and n  How does processor know which location is relevant at a given point in the computation?  Answer: Frame Base Register  When a method is invoked, a frame is created for that method invocation, and FBR is set to point to that frame  When the invocation returns, FBR is restored to what it was before the invocation  How does machine know what value to restore in the FBR?  This is part of the return info in the stack frame

FBR 31  Computational activity takes place only in the topmost (most recently pushed) stack frame return info (a = ) 2 (n = ) 5 (hP = ) ? return info (a = ) 2 (n = ) 5 (hP = ) ? return info (a = ) 2 (n = ) 2 (hP = ) ? return info (a = ) 2 (n = ) 5 (hP = ) ? return info (a = ) 2 (n = ) 2 (hP = ) ? return info (a = ) 2 (n = ) 1 (hP = ) ? FBR old FBR

Conclusion 32  Recursion is a convenient and powerful way to define functions  Problems that seem insurmountable can often be solved in a “divide-and-conquer” fashion:  Reduce a big problem to smaller problems of the same kind, solve the smaller problems  Recombine the solutions to smaller problems to form solution for big problem  Important application (next lecture): parsing