Recursion CMPE231, Spring 2012 Aleaxander G. Chefranov 1.

Slides:



Advertisements
Similar presentations
Towers of Hanoi Move n (4) disks from pole A to pole C such that a disk is never put on a smaller disk A BC ABC.
Advertisements

COSC 2006 Data Structures I Recursion III
Factorial Recursion stack Binary Search Towers of Hanoi
Recursive methods. Recursion A recursive method is a method that contains a call to itself Often used as an alternative to iteration when iteration is.
Lesson 19 Recursion CS1 -- John Cole1. Recursion 1. (n) The act of cursing again. 2. see recursion 3. The concept of functions which can call themselves.
Recursion. Idea: Some problems can be broken down into smaller versions of the same problem Example: n! 1*2*3*…*(n-1)*n n*factorial of (n-1)
CS102 Algorithms and Programming II1 Recursion Recursion is a technique that solves a problem by solving a smaller problem of the same type. A recursive.
Recursion. Binary search example postponed to end of lecture.
1 CSCD 300 Data Structures Recursion. 2 Proof by Induction Introduction only - topic will be covered in detail in CS 320 Prove: N   i = N ( N + 1.
Chapter 10 Recursion Dr. Jiung-yao Huang Dept. Comm. Eng. Nat. Chung Cheng Univ. TA: 鄭筱親 陳昱豪.
Recursion. Learn about recursive definitions Explore the base case and the general case of a recursive definition Learn about recursive algorithms Lecture.
1 Chapter 1: Introduction What you have learnt in Comp1220 or Comp1170? What will be taught in Comp 1200? - more Abstract Data Types -efficient algorithms.
Recursion Gordon College CPS212
Chapter 10 Recursion. Copyright © 2005 Pearson Addison-Wesley. All rights reserved Chapter Objectives Explain the underlying concepts of recursion.
Recursion.
FIT FIT1002 Computer Programming Unit 20 Recursion.
Review of Recursion What is a Recursive Method? The need for Auxiliary (or Helper) Methods How Recursive Methods work Tracing of Recursive Methods.
Chapter 15 Recursive Algorithms. 2 Recursion Recursion is a programming technique in which a method can call itself to solve a problem A recursive definition.
Recursion A recursive function is a function that calls itself either directly or indirectly through another function. The problems that can be solved.
CENG 7071 Recursion. CENG 7072 Recursion Recursion is a technique that solves a problem by solving a smaller problem of the same type. A recursive function.
Recursion Chapter 7 Copyright ©2012 by Pearson Education, Inc. All rights reserved.
Chapter 14: Recursion Starting Out with C++ Early Objects
Recursion Chapter Nature of Recursion t Problems that lend themselves to a recursive solution have the following characteristics: –One or more.
Chapter 2 Recursion: The Mirrors CS Data Structures Mehmet H Gunes Modified from authors’ slides.
Copyright © 2007 Pearson Education, Inc. Publishing as Pearson Addison-Wesley Chapter 12: Recursion Problem Solving, Abstraction, and Design using C++
C++ Programming: From Problem Analysis to Program Design, Third Edition Chapter 17: Recursion.
Chapter 13 Recursion. Topics Simple Recursion Recursion with a Return Value Recursion with Two Base Cases Binary Search Revisited Animation Using Recursion.
Recursion.
3 -1 Chapter 3 Recursion Iterative algorithm for n factorial n factorial n! = 1 if n = 0 n! = n*(n-1)*(n-2)*...*1 if n>0 Iterative algorithm prod.
JAVA: An Introduction to Problem Solving & Programming, 5 th Ed. By Walter Savitch and Frank Carrano. ISBN © 2008 Pearson Education, Inc., Upper.
1 Recursion Algorithm Analysis Standard Algorithms Chapter 7.
Chapter 9: Recursion1 CHAPTER 9 RECURSION. Recursion  Concept of recursion  A recursive: Benefit and Cost  Comparison : Iterative and recursive functions.
Data Structures and Abstractions with Java, 4e Frank Carrano
CHAPTER 02 Recursion Compiled by: Dr. Mohammad Omar Alhawarat.
Lecturer: Dr. AJ Bieszczad Chapter 11 COMP 150: Introduction to Object-Oriented Programming 11-1 l Basics of Recursion l Programming with Recursion Recursion.
1 Chapter 13 Recursion. 2 Chapter 13 Topics l Meaning of Recursion l Base Case and General Case in Recursive Function Definitions l Writing Recursive.
1 Recursion. 2 Chapter 15 Topics  Meaning of Recursion  Base Case and General Case in Recursive Function Definitions  Writing Recursive Functions with.
Recursion Textbook chapter Recursive Function Call a recursive call is a function call in which the called function is the same as the one making.
Sudeshna Sarkar, IIT Kharagpur 1 Functions : Recursion Lecture
1 7.Algorithm Efficiency What to measure? Space utilization: amount of memory required  Time efficiency: amount of time required to process the data Depends.
Computer Science Department Data Structure & Algorithms Lecture 8 Recursion.
Chapter 14 Recursion. Chapter Objectives Learn about recursive definitions Explore the base case and the general case of a recursive definition Learn.
Review Introduction to Searching External and Internal Searching Types of Searching Linear or sequential search Binary Search Algorithms for Linear Search.
Chapter 4 Recursion. Copyright © 2004 Pearson Addison-Wesley. All rights reserved.1-2 Chapter Objectives Explain the underlying concepts of recursion.
Recursion Part 3 CS221 – 2/27/09. Recursion A function calls itself directly: Test() { … Test(); … }
1 7.Algorithm Efficiency What to measure? Space utilization: amount of memory required  Time efficiency: amount of time required to process the data.
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.
Java Programming: Guided Learning with Early Objects Chapter 11 Recursion.
©TheMcGraw-Hill Companies, Inc. Permission required for reproduction or display. Chapter 15 * Recursive Algorithms.
Chapter 11Java: an Introduction to Computer Science & Programming - Walter Savitch 1 Chapter 11 l Basics of Recursion l Programming with Recursion Recursion.
1 Recursion. 2 Chapter 15 Topics  Meaning of Recursion  Base Case and General Case in Recursive Function Definitions  Writing Recursive Functions with.
CSE 251 Dr. Charles B. Owen Programming in C1 Functions.
1 Recursive algorithms Recursive solution: solve a smaller version of the problem and combine the smaller solutions. Example: to find the largest element.
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.
chap10 Chapter 10 Recursion chap10 2 Recursive Function recursive function The recursive function is a kind of function that calls.
1 7.Algorithm Efficiency These factors vary from one machine/compiler (platform) to another  Count the number of times instructions are executed So, measure.
1 CSC 143 Recursion [Reading: Chapter 17]. 2 Recursion  A recursive definition is one which is defined in terms of itself.  Example:  Sum of the first.
Lecture 11 Recursion. A recursive function is a function that calls itself either directly, or indirectly through another function; it is an alternative.
1 Dr. Chow-Sing LinRecursion - CH 10 Problem Solving and Program Design in C Chapter 9 Recursion Chow-Sing Lin.
Chapter 9 Recursion. Copyright ©2004 Pearson Addison-Wesley. All rights reserved.10-2 Recursive Function recursive functionThe recursive function is –a.
Recursion.
Chapter 15 Recursion.
Recursion DRILL: Please take out your notes on Recursion
Chapter 10 Recursion Dr. Jiung-yao Huang Dept. Comm. Eng.
Chapter 15 Recursion.
CS201: Data Structures and Discrete Mathematics I
Recursion Data Structures.
7.Recursion Recursion is the name given for expression anything in terms of itself. Recursive function is a function which calls itself until a particular.
CSC 143 Recursion.
Chapter 18 Recursion.
Presentation transcript:

Recursion CMPE231, Spring 2012 Aleaxander G. Chefranov 1

Recursive Definition and Processes π is defined as the ratio of the circumference of a circle to its diameter Factorial N! is defined as the product of integers between n and 1 N!=1 if n=0 N!=n(n-1)..2*1 if n>0 Prod=1; For(x=n;x>0;x--) prod*=x; Return prod; Iterative algorithm 2

Recursive Definition and Processes N!=1 if n=0 N!=n*(n-1)! If n>0 Recursive definition If(n==0) fact=1; Else{ x=n-1; find the value of X!. Call it y; fact=n*y; }/*end else*/ 3

Examples Multiplication of natural numbers A*b=a if b==1 A*b=a*(b-1)+a if b>1 Fibonacci Sequence Fib(n)=n if n==0 or n==1 Fib(n)=fib(n-2)+fib(n-1) if n>=2 If(n<=1) return n; Lofib=0; Hifib=1; For(i=2;i<=n;i++){ x=lofib; lofib=hifib; hifib=x+lofib; }/* end for*/ Return hifib; 4

Examples Binary Search Recursive algorithm to search a sorted array a for an element x between a[low] and a[high]. The algorithm returns an index of a such that a[index] equals x if such an index exists between low and high. If x is not found in that portion of the array, binsrch returns -1 (in C, no element a[-1] can exist) If (low>high) return -1; Mid=(low+high)/2; If(x==a[mid]) return mid; If (x<a[mid]) search for x in a[low] to a[mid-1]; Else search for x in a[mid+1] to a[high]; 5

Properties of Recursive definitions of Algorithms It is not to generate an infinite sequence of calls to itself There must be a way out of the sequence of recursive calls Factorial: 0!=1 Multiplication: a*1=a Fibonacci seq.: fib(0)=0; fib(1)=1; Binary search: if(low>high)return -1; if(x==a[mid]) return mid; Any invocation of a recursive algorithm must eventually reduce to some manipulation of one or more simple, or nonrecursive cases. 6

Recursion in C Int fact(int n){ int x,y; if(n==0) return 1; x=n-1; y=fact(x); return n*y; }/*end fact*/ 7

Recursion in C Stack is used to keep the successive generations of local variables and parameters Each time, a recursive function is entered, a new allocation of its variables is pushed on top of the stack. Any reference to a local variable is through the current top of the stack. When the function returns, the stack is popped, the top allocation is freed, and the previous allocation becomes the current stack top to be used for referencing local variables 8

Recursion in C Int mult(int a, int b){ return(b==1?a:mult(a,b-1)+a); }/*end mult*/ Int fact(int n){ return(n==0?1:n*fact(n-1)); }/*end fact*/ 9

Recursion in C Int fib(int n){ int x,y; if(n<=1) return n; x=fib(n-1); y=fib(n-2); return (x+y); }/*end fib*/ 10

Recursion in C Int binsrch(int a[], int x, int low, int high){ int mid; if (low>high) return -1; mid=(low+high)/2; return(x==a[mid]?mid:x<a[mid]? binsrch(a,x,low,mid-1): binsrch(a,x,mid+1,high); }/*end binsrch*/ Int a[ARRAYSIZE]; i=binsrch(a,x,0,n-1); Global variables may be used instead of parameters Int a[ARRAYSIZE], x; i=binsrch(0,n-1); Int binsrch(int low, int high); 11

Recursive Chains A(formal parameters){.. b(arguments);.. }/*end of a*/ b(formal parameters){.. a(arguments);.. }/*end of b*/ 12

Recursive Definition of Algebraic Expressions An expression is a term followed by a plus sign, or a term alone A term is a factor followed by an asterisk followed by a factor, or a factor alone A factor is either a letter or an expression enclosed in parenthesis Int getsymb(char str[],int length,int *ppos){ char c; if(*ppos<length) c=str[*ppos]; else c=‘ ‘; (*ppos)++; return c; } 13

Expressions #include #define TRUE 1 #define FALSE 0 #define MAXSTRSIZE 100 Void readstr(char *, int); Int expr(char *, int, int *); Int term(char *, int, int *); Int getsymb(char *, int, int *); Int factor(char *, int, int *); 14

Expressions (cont 1) Void main(){ char str[MAXSTRSIZE]; int length, pos; readstr(str, &length); pos=0; if(expr(str, length, &pos)==TRUE && pos>=length) printf(“Valid\n”); else printf (“Invalid\n”); }/*end main*/ 15

Expressions (cont 2) Int expr(char str[], int length, int *ppos){ if(term(str, length, ppos)==FALSE) return FALSE; if(getsymb(str, length, ppos)!=‘+’){ (*ppos)--; return TRUE; } return term(str, length, ppos); }/*end expr*/ 16

Expressions (cont 3) Int term(char str[], int length, int *ppos){ if(factor(str, length, ppos)==FALSE) return FALSE; if(getsymb(str, length, ppos)!=‘*’){ (*ppos)--; return TRUE; } return factor(str, length, ppos); }/*end term*/ 17

Expressions (cont 4) Int factor(char str[], int length, int *ppos){ int c; if((c=getsymb(str,length,ppos))!=‘(‘) return isalpha(c); return expr(str, length, ppos) && getsymb(str, length, ppos)==‘)’); }/*end factor*/ 18

Towers of Hanoi Problem Three pegs, A, B, and C, exist. Five disks of differing diameters are placed on peg A so that a larger disk is always below a smaller disk. The object is to move the five disks to peg C, using peg B as auxiliary. Only the top disk on any peg may be moved to any other peg, and a larger disk may never rest on a smaller one. 19

Towers of Hanoi Problem Let’s consider general case of n disks. Suppose that we had a solution for n-1 disks and could state solution for n disks in terms of the solution for n-1 disks. Then the problem would be solved. This is true because in the trivial case of one disk (continually subtracting 1 from n will eventually produce 1), the solution is simple: merely move the single disk from peg A to peg C. 20

Towers of Hanoi Problem Move n disks from A to C using B as auxiliary 1.If n==1, move the single disk from A to C and stop 2.Move the top n-1 disks from A to B, using C as auxiliary 3.Move the remaining disk from A to C 4.Move the n-1 disks from B to C, using A as auxiliary 21

Towers of Hanoi Problem How to represent actions? Design of inputs and outputs If necessary, a programmer can convert internal representation to the user’s form Output: Move disk nnn from peg yyy to peg zzz The action to be taken for a solution would be to perform each of the output statements in the order they appear in the output 22

Towers of Hanoi Problem What shall be parameters of the function? Void main(){ int n; scanf(“%d”, &n); towers(paramters); }/*end main*/ 23

Towers of Hanoi Problem #include Void towers(int n, char frompeg, char topeg, char auxpeg); Void main(){ int n; scanf(“%d”, &n); towers(n, ‘a’,’c’,’b’); }/*end main*/ 24

Towers of Hanoi Problem Void towers(int n, char frompeg, char topeg, char auxpeg){ if(n==1){ printf(“\nmove disk 1 from peg %c to peg %c”, frompeg, topeg); return; }/*end if*/ towers(n-1, frompeg, auxpeg, topeg); printf(“\nmove disk %d from peg %c to peg %c”, n,frompeg, topeg); towers(n-1,auxpeg, topeg, frompeg); }/*end towers*/ 25

Towers of Hanoi Problem Move disk 1 from peg a to peg b Move disk 2 from peg a to peg c Move disk 1 from peg b to peg c Move disk 3 from peg a to peg b Move disk 1 from peg c to peg a Move disk 2 from peg c to peg b Move disk 1 from peg a to peg b Move disk 4 from peg a to peg c Move disk 1 from peg b to peg c Move disk 2 from peg b to peg a Move disk 1 from peg c to peg a Move disk 3 from peg b to peg c Move disk 1 from peg a to peg b Move disk 2 from peg a to peg c Move disk 1 from peg b to peg c 26

Efficiency of Recursion In general, a nonrecursive version of a program will execute more efficiently in terms of time and space than a recursive version. This is because overhead involved in entering and exiting a block is avoided in the nonrecursive version. However, sometimes a recursive solution is the most natural and logical way of solving a problem. A nonrecursive solution involving stacks is more difficult to develop and and mor prone to errors 27

Efficiency of Recursion Thus there is a conflict between machine efficiency and programmer efficiency. If a program is to be run very frequently, so that increased efficiency in execution speed significantly increases throughput, the extra investment in programming is worthwhile. Even in such cases, it is better to have at first recursive version, and then modify it to a nonrecursive one. 28