Recursion Introduction A Recursive Definition One Defined in

  • Slides: 25
Download presentation
Recursion Introduction A Recursive Definition … One Defined in Terms of Itself Recursion is

Recursion Introduction A Recursive Definition … One Defined in Terms of Itself Recursion is an important problem solving tool in Computer science Mathematics Recursion occurs when we solve a problem. . . ¨ By partitioning it into smaller sub-problems ¨ That are solved by applying the same algorithm With recursion we use the familiar divide and conquer paradigm We can have recursive · Procedures or algorithms · Data structures · Definitions 1

Recursion Introduction A Recursive Definition … One Defined in Terms of Itself Compound interest

Recursion Introduction A Recursive Definition … One Defined in Terms of Itself Compound interest The value after 10 years is equal to the interest rate times the value after 9 years. ” A phrase is a "palindrome" If the 1 st and last letters are the same and What's inside is itself a palindrome (or is empty). Copyright 2001 Oxford Consulting, Ltd 2 1 January 2001

Recursion Introduction A Recursive Procedure … One that Invokes Itself char Insist. On. Yor.

Recursion Introduction A Recursive Procedure … One that Invokes Itself char Insist. On. Yor. N (void) { char answer; cout << "Please enter y or n: ” << endl; cin >> answer; switch (answer) { case 'y': return 'y'; case 'n': return 'n'; } } default: return Insist. On. Yor. N( ); 3

Recursion Introduction Recursive Data Structures A data structure may contain a pointer to an

Recursion Introduction Recursive Data Structures A data structure may contain a pointer to an instance of the same type struct Node { int data; Node *next; } ; 4

Recursion Introduction Recursive Definitions If A and B are arithmetic expressions…. then (A) +

Recursion Introduction Recursive Definitions If A and B are arithmetic expressions…. then (A) + (B) is a valid expression 5

Recursion Introduction Recursive Definitions - Factorial n! ( “n factorial” ) can be defined

Recursion Introduction Recursive Definitions - Factorial n! ( “n factorial” ) can be defined in two ways: · Non-recursive definition n! = n * (n-1) (n-2) … * 2 * 1 · Recursive definition 1, if n = 1 n! = n * (n-1)! , if n > 1 0! is usually defined to be 1 Undefined for negative numbers 6

Recursion Introduction Recursive Definitions How do we write a function that reflects the recursive

Recursion Introduction Recursive Definitions How do we write a function that reflects the recursive definition? The factorial function invokes itself. How can this work? int factorial(int n) { assert(n >= 1); if ( n == 1 ) return 1; else return n * factorial(n-1); } 7

Recursion Introduction Recursive Problems or Games Towers of Hanoi Three Pegs Object is to

Recursion Introduction Recursive Problems or Games Towers of Hanoi Three Pegs Object is to move disks from one peg to a second Rules · Can only move 1 disk at a time · Large disk cannot go on top of a smaller one Mazes Can be easily solved in a recursive manner 8

Recursion Recursive Definitions - What Makes Recursion Work? Local variables and formal parameters are

Recursion Recursive Definitions - What Makes Recursion Work? Local variables and formal parameters are Allocated when { } block is entered, Deleted when block is exited. Whenever a function is called, a new activation record is created, containing: · A separate copy of all local variables and parameters · Control information, such as where to return to The activation record is alive until the function returns, then it is destroyed This applies whether or not function is recursive! 9

Recursion Recursive Definitions - What Makes Recursion Work? A Very Simplified Model. . .

Recursion Recursive Definitions - What Makes Recursion Work? A Very Simplified Model. . . Every time you call a function, you get a fresh copy of it If you call recursively, you end up with more than one copy of the function active When you exit a function, Only that copy of it goes away In reality. . . There's only one copy of the code (instructions), but separate copies of the data (variables, parameters) 10

Recursion Recursive Definitions - What Makes Recursion Work? Tracing the Process. . . To

Recursion Recursive Definitions - What Makes Recursion Work? Tracing the Process. . . To trace function calls · Draw a box each time a function is called. · Draw an arrow from caller to callee · Label data (local variables, parameters) inside the box · Indicate the returned value (if any) · Cross out the box after return and don't reuse it! 11

Recursion Recursive Definitions - What Makes Recursion Work? int factorial(int n) { if (

Recursion Recursive Definitions - What Makes Recursion Work? int factorial(int n) { if ( n == 1 ) return 1; else return n * factorial(n-1); } … int main (void) { int x = factorial(4); cout << “ 4! = “ << x << endl; . . . 12

Recursion Recursive Definitions What is Recursion? • A programming technique, a function calling itself

Recursion Recursive Definitions What is Recursion? • A programming technique, a function calling itself • An approach to problem-solving, look for smaller problems similar to the larger problem • A way of thinking about algorithms turns out to lead to good mathematical analyses • The natural algorithmic technique when recursive data structures are involved Recursion takes practice Eventually it becomes a natural habit of thought 13

Recursion Recursive Definitions Infinite Recursion Mathematically, n! = n * (n-1)! = (n-1)! *

Recursion Recursive Definitions Infinite Recursion Mathematically, n! = n * (n-1)! = (n-1)! * n Why not program it in that order? int bad. Factorial (n) { int x = bad. Factorial (n-1); if ( n == 1 ) return 1; else return n * x; } What is the value of bad. Factorial(2)? The Rule: Must always have some way to make recursion stop, otherwise it runs forever 14

Recursion Recursive Definitions A Recursive Procedure … Using Recursion Correctly For correct recursion …

Recursion Recursive Definitions A Recursive Procedure … Using Recursion Correctly For correct recursion … we need two parts: 1. One or more base cases that are not recursive if ( n == 1 ) return 1; // no recursion in this case 2. One or more recursive cases that operate on smaller problems that get closer to a base case return n * factorial(n-1); // factorial(n-1) is a smaller // problem than factorial (n) Note: The base case(s) should always be checked before the recursive calls 15

Recursion Recursive Definitions Kick-Off and Helper Functions To make recursion work properly we have

Recursion Recursive Definitions Kick-Off and Helper Functions To make recursion work properly we have a common pattern · Top-level kick-off function Not itself recursive Starts the recursion going Returns the ultimate answer · Helper function Contains the actual recursion May require additional parameters to keep track of the recursion Client programs only need call the kick-off function 16

Recursion Recursive Definitions Recursion with Array Parameters double sum (double i. Array [ ],

Recursion Recursive Definitions Recursion with Array Parameters double sum (double i. Array [ ], int from, int to) { // find sum of all elements in array between index from and index to if (from > to) return 0. 0; return i. Array[ from ] + sum ( i. Array, from+1, to ); } // Client code: double Cash. Values[200]; . . . double total = sum (Cash. Values, 0, 199); Implemented without kick-off/helper structure but probably would benefit from having it 17

Recursion Recursive Definitions Recursion vs. Iteration When to use recursion? Processing recursive data structures

Recursion Recursive Definitions Recursion vs. Iteration When to use recursion? Processing recursive data structures Divide and Conquer algorithms: 1. Divide problem into subproblems 2. Solve each subproblem recursively 3. Combine subproblem solutions When to use iteration instead? Nonrecursive data structures Problems without obvious recursive structure Functions with a large footprint Especially when many iterations are needed 18

Recursion Recursive Definitions Recursion vs. Iteration In Theory. . . Any iteration can be

Recursion Recursive Definitions Recursion vs. Iteration In Theory. . . Any iteration can be rewritten using recursion, and vice-versa (at least in theory) …But the rewrite is not always simple! Iteration is generally more efficient Faster Takes less memory A compromise: If the problem is naturally recursive, design the algorithm recursively first Later convert to iteration if needed for efficiency General Principle: Make it right, then make it efficient 19

Recursion Recursive Definitions Recursion vs. Iteration - Tail Recursion Suppose the last action of

Recursion Recursive Definitions Recursion vs. Iteration - Tail Recursion Suppose the last action of a function is to make a call to itself In a stack based implementation…. . 1. Local variables pushed onto the stack as recursive call is initiated 2. When recursive call terminates, the local variables will be popped off and restored to their former values Doing this last step is pointless since the recursive call is the last operation of function…. The values that were just restored are discarded 20

Recursion Recursive Definitions Recursion vs. Iteration - Tail Recursion When last action of function

Recursion Recursive Definitions Recursion vs. Iteration - Tail Recursion When last action of function is recursive call to itself It is not necessary to use the stack since no local variables need to be saved Instead, set dummy calling parameters to new values and branch to the beginning of the function 21

Recursion Recursive Definitions Recursion vs. Iteration - Tail Recursion If last executed statement of

Recursion Recursive Definitions Recursion vs. Iteration - Tail Recursion If last executed statement of a function is a recursive call to the function itself, the call can be eliminated by assigning the calling parameters to the values specified in the recursive call then repeating the whole function. A single recursive call at the very end of the function is known as tail recursion 22

Recursion Recursive Definitions Recursion vs. Iteration - Avoiding Recursion So Should we avoid recursion?

Recursion Recursive Definitions Recursion vs. Iteration - Avoiding Recursion So Should we avoid recursion? 1. If we have tail recursion…. It’s easy for a smart compiler to automatically rewrite using iteration 2. Recursive problems that are not tail recursive are harder to automatically rewrite non-recursively Usually have to simulate recursion with a stack 23

Recursion Recursive Definitions Recursion vs. Iteration - Avoiding Recursion It’s important to recognize the

Recursion Recursive Definitions Recursion vs. Iteration - Avoiding Recursion It’s important to recognize the following, Some programming languages provide no iteration control statements Loops must be implemented through recursion Rely on the compiler to make it efficient Prolog, pure LISP Not all programming languages support recursion! COBOL, FORTRAN (at least early versions) Many highly paid programmers never use recursion So. . . why do we make you do it? ? 24

Recursion Recursive Definitions Summary · Recursion is something defined in terms of itself ·

Recursion Recursive Definitions Summary · Recursion is something defined in terms of itself · Activation records make it work · Elements of recursive functions · Base case(s) · Recursive case(s) · Base case always checked first · When to use/when to avoid 25