Maitrayee Mukerji. Factorial For any positive integer n, its factorial is n! is: n! = 1 * 2 * 3 * 4* ….* (n-1) * n 0! = 1 1 ! = 1 2! = 1 * 2 = 2 5! =

Slides:



Advertisements
Similar presentations
 2003 Prentice Hall, Inc. All rights reserved. 1 Recursion Recursive functions –Functions that call themselves –Can only solve a base case If not base.
Advertisements

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. Binary search example postponed to end of lecture.
C++ Programming: Program Design Including Data Structures, Third Edition Chapter 16: Recursion.
Scott Grissom, copyright 2004 Chapter 5 Slide 1 Analysis of Algorithms (Ch 5) Chapter 5 focuses on: algorithm analysis searching algorithms sorting algorithms.
Copyright © 2008 Pearson Education, Inc. Publishing as Pearson Addison-Wesley Starting Out with C++ Early Objects Sixth Edition Chapter 14: Recursion by.
Recursion CS-240/CS341. What is recursion? a function calls itself –direct recursion a function calls its invoker –indirect recursion f f1 f2.
Chapter 19 Recursion.
Starting Out with C++: Early Objects 5/e © 2006 Pearson Education. All Rights Reserved Starting Out with C++: Early Objects 5 th Edition Chapter 14 Recursion.
Recursion A recursive function is a function that calls itself either directly or indirectly through another function. The problems that can be solved.
Copyright © 2008 Pearson Education, Inc. Publishing as Pearson Addison-Wesley Starting Out with Java: Early Objects Third Edition by Tony Gaddis Chapter.
Copyright © 2009 Pearson Education, Inc. Publishing as Pearson Addison-Wesley Chapter 19: Recursion.
Nirmalya Roy School of Electrical Engineering and Computer Science Washington State University Cpt S 122 – Data Structures Recursion Review.
Copyright © 2014, 2008 Pearson Education, Inc. Publishing as Pearson Addison-Wesley Starting Out with C++ Early Objects Eighth Edition by Tony Gaddis,
Copyright 2003 Scott/Jones Publishing Standard Version of Starting Out with C++, 4th Edition Chapter 19 Recursion.
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.
 2003 Prentice Hall, Inc. All rights reserved. 1 Functions and Recursion Outline Function Templates Recursion Example Using Recursion: The Fibonacci Series.
1 Object-Oriented Programming Using C++ CLASS 2. 2 Linear Recursion Summing the Elements of an Array Recursively Algorithm LinearSum(A, n): Input: An.
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.
CMSC 2021 Recursion Recursive Definition – one that defines something in terms of itself Recursion – A technique that allows us to break down a problem.
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.
© 2010 Pearson Addison-Wesley. All rights reserved. Addison Wesley is an imprint of Chapter 15: Recursion Starting Out with Java: From Control Structures.
Copyright © 2011 Pearson Education, Inc. Starting Out with Java: Early Objects Fourth Edition by Tony Gaddis Chapter 14: Recursion.
Copyright © 2015 Pearson Education, Inc. Publishing as Pearson Addison-Wesley C H A P T E R 12 Recursion.
Chapter 9: Recursion1 CHAPTER 9 RECURSION. Recursion  Concept of recursion  A recursive: Benefit and Cost  Comparison : Iterative and recursive functions.
Programming Principles II Lecture Notes 5 Recursion Andreas Savva.
Recursive. 2 Recursive Definitions In a recursive definition, an object is defined in terms of itself. We can recursively define sequences, functions.
Chapter 12 Recursion, Complexity, and Searching and Sorting
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.
C++ Programming: From Problem Analysis to Program Design, Fourth Edition Chapter 17: Recursion.
Review Introduction to Searching External and Internal Searching Types of Searching Linear or sequential search Binary Search Algorithms for Linear Search.
Chapter 13 Recursion. Learning Objectives Recursive void Functions – Tracing recursive calls – Infinite recursion, overflows Recursive Functions that.
Recursion Part 3 CS221 – 2/27/09. Recursion A function calls itself directly: Test() { … Test(); … }
Advanced Computer Architecture and Parallel Processing Rabie A. Ramadan http:
Edited by Malak Abdullah Jordan University of Science and Technology Data Structures Using C++ 2E Chapter 6 Recursion.
Java Programming: Guided Learning with Early Objects Chapter 11 Recursion.
Functions-Recall 1. 2 Parameter passing & return void main() { int x=10, y=5; printf (“M1: x = %d, y = %d\n”, x, y); interchange (x, y); printf (“M2:
Lecture 7. Solution by Substitution Method T(n) = 2 T(n/2) + n Substitute n/2 into the main equation 2T(n/2) = 2(2(T(n/4)) + n/2) = 4T(n/4) + n And T(n)
1 Recursion n what is it? n how to build recursive algorithms n recursion analysis n tracing simple recursive functions n hands on attempts at writing.
© Janice Regan, CMPT 128, February CMPT 128: Introduction to Computing Science for Engineering Students Recursion.
C++ Programming: Program Design Including Data Structures, Fourth Edition Chapter 16: Recursion.
23 February Recursion and Logarithms CSE 2011 Winter 2011.
Pei Zheng, Michigan State University 1 Chapter 8 Recursion.
Starting Out with C++, 3 rd Edition Chapter 19 Recursion.
JAVA: An Introduction to Problem Solving & Programming, 7 th Ed. By Walter Savitch ISBN © 2015 Pearson Education, Inc., Upper Saddle River,
1 Chapter 8 Recursion. 2 Recursive Function Call a recursion function is a function that either directly or indirectly makes a call to itself. but we.
1 Recursion Recursive function: a function that calls itself (directly or indirectly). Recursion is often a good alternative to iteration (loops). Its.
CS 116 Object Oriented Programming II Lecture 13 Acknowledgement: Contains materials provided by George Koutsogiannakis and Matt Bauer.
Program Development and Design Using C++, Third Edition
Chapter 9 Recursion. Copyright ©2004 Pearson Addison-Wesley. All rights reserved.10-2 Recursive Function recursive functionThe recursive function is –a.
Chapter Topics Chapter 16 discusses the following main topics:
Chapter 19: Recursion.
Topic 6 Recursion.
Recursion what is it? how to build recursive algorithms
Chapter 15 Recursion.
Chapter 10 Recursion Instructor: Yuksel / Demirer.
Recursion A problem solving technique where an algorithm is defined in terms of itself A recursive method is a method that calls itself A recursive algorithm.
Chapter 15 Recursion.
Chapter 14: Recursion Starting Out with C++ Early Objects
Recursion "To understand recursion, one must first understand recursion." -Stephen Hawking.
Chapter 14: Recursion Starting Out with C++ Early Objects
Stack Frames and Functions
Programming with Recursion
Recursive Algorithms 1 Building a Ruler: drawRuler()
Presentation transcript:

Maitrayee Mukerji

Factorial For any positive integer n, its factorial is n! is: n! = 1 * 2 * 3 * 4* ….* (n-1) * n 0! = 1 1 ! = 1 2! = 1 * 2 = 2 5! = 1 * 2 * 3 * 4 * 5 = ! = 1 * 2 * 3 * 4 * 5 * 6 * 7 * 8 * 9 * 10 =

Contd… int Factorial (int n) {fac = 1; for (i=2; i <= n; i++) fac = fac * n; return (fac) } main () { cin >> n; int nfac = Factorial (n); cout << nfac; return 0; } => Iterative Implementation, loop is used to accomplish the task

Example..contd. Another way of looking at factorial is: 5! = 5 * 4 * 3 * 2 * 1 = 5 * 4! = 5 * 4 * 3! = 5 * 4 * 3 * 2! = 5 * 4 * 3 * 2 * 1! = 5 * 4 * 3 * 2 * 1 In general, factorial of any integer n is: n! = n * (n-1)!

Factorial: Recursive Definition Base Case Recursive Case 1 if n = 0 n! = n * (n-1) ! if n> 0

Example – Factorial Recursive int factorial (int n) {if n == 0 then return (1); else return ( n * factorial (n-1)); }

Recursion – Example void Print(int k) {cout << k; Print(k + 1); } main {Print (2); }

void Print2(int k) { if (k < 0) return; cout << k; Print2(k + 1); } main { Print2 (2); }

Print(int k) { if (k == 0) { return; } cout<< (k); Print(k - 1); } main {Print (2); }

Recursion Recursion : when a function refers to itself in its own definition When one function calls itself rather than some other functions, it is said to be a recursive function The method in which a problem is solved by reducing it to smaller cases of the same problem Provides an elegant and powerful alternative for performing repetitive tasks

Types of Recursion Linear Recursion Binary Recursion Non-linear Recursion Mutual Recursion

Linear Recursion Recursive algorithm in which only one internal recursive call is made within the body of the function. General Framework Function linear () {if “termination condition satisfied” then return some value else {perform some action make a further recursive call to linear() } Examples: Factorial, Greatest Common Divisor

Example: Reversing an Array Input: An array A and nonnegative integer indices i and j Output: The reversal of the elements in A starting at index i and ending at j ReverseArray(A, i, j) {if i < j then {Swap A[i] and A[ j] ReverseArray(A, i+1, j−1) return } } main() {ReverseArray(A, 0,n-1) }

Example: GCD The greatest common divisor (gcd) of two or more integers (at least one of which is not zero), is the largest positive integer that divides the numbers without a remainder Divisors (8) = 1, 2, 4, 8 Divisors (12) = 1, 2, 3, 4, 6, 12 Common Divisors = 1,2, 4 GCD (8,12) = 4

GCD…Euclid Algorithm Suppose d is a common divisor of two integers X and Y where X>Y Then X = q 1 d and Y = q 2 d => X-Y = q 1 d - q 2 d = (q 1 - q 2 )d = q 3 d => d is also a divisor of X-Y Euclid Algorithm GCD (X,Y) == GCD(Y, X-Y) E.g. GCD (20,12) = GCD (12,8) == GCD (8,4) == GCD (4,4) = 4

GCD..Euclid Algorithm Assuming two positive integers X, Y and X> Y int GCD (X,Y) {while (Y!=0) {r = X mod Y X = Y Y = r } return X } => Iterative Algorithm GCD (20,12) XYr GCD (20,12) = 4

GCD … Recursive Algorithm int gcd(int X, int Y) {if Y== 0 then gcd = X; else gcd = gcd (Y, X mod Y); return gcd; }

Recursive Trace/Depth of Recursion GCD (24, 18) GCD (18, 6) GCD (6,0) 6 6 6

Recursive Trace/Depth of Recursion Factorial (4) Factorial (3) Factorial (2) Factorial (1) Factorial (0) Depth of Recursion = 5

Call Stack This is how method calls (recursive and non-recursive) really work: At runtime, a stack of activation records (ARs) is maintained: one AR for each active method, where "active" means: has been called, has not yet returned. This stack is also referred to as the call stack. Each AR includes space for: the method's parameters, the method's local variables, the return address -- where (in the code) to start executing after the method returns. When a method is called, its AR is pushed onto the stack. The return address in that AR is the place in the code just after the call. When a method is about to return, its AR is popped from the stack, and control is transferred to the place in the code referred to by the return address.

Example: non-recursive function 1. void printChar (char c) 2. { cout << c; 3. } 4. void main (... ) 5. { char ch = 'a'; 6. printChar(ch); 7. ch = 'b'; 8. printChar(ch); 9. } Main ‘s AR ch = “a” Return add: System Call Stack PrintChar ‘s AR ch = “a” Return add: Line 7 PrintChar ‘s AR ch = “b” Return add: Line 9 Main ‘s AR ch = “b” Return add: System

Example: recursive function 1.void printInt( int k ) 2.{ if (k <= 0) return; 3. cout<< k ; 4. printInt( k - 1 ); 5. } 6. void main(... ) 7.{ printInt( 2 ); 8.} PrintInt ‘s AR k = “2” Return add: Line 8 Main ‘s AR Return add: System 2 PrintInt ‘s AR k = “1” Return add: Line 5 1 PrintInt ‘s AR k = “0” Return add: Line 5

exercise 1. void printInt(int k) { 2. if (k <= 0) return; 3. printInt (k – 1); 4. cout << k; 5. } 6. void main(... ) 7. { printInt( 2 ); 8.}

Drawbacks of Linear Recursion Greater risk of incurring large depth of recursion Each recursive call requires the saving of an additional set of parameter, local variables and links Thus recursive algorithms can be much more expensive in use of memory than simple iterative solutions This overhead can make linearly recursive algorithms slower than more concise iterative versions

Binary Recursion An algorithm that makes two internal recursive calls to itself A problem is solved by first breaking it down into two smaller problems that are each in turn solved by being broken into two still smaller problems, and so on recursively Wide applications and importance Recursively defined data structures eg. Fibonacci Series, Binary Tree Traversal, Binary Search, Quicksort

Binary Recursion function binary () { if “termination condition” met then perform some action(s) and/or return some value else { (1) perform some actions (2) make a recursive call to binary() that solves one of the two smaller problems (3)make another recursive call to binary() to solve the other small problem }

Binary Recursion - Example Fibonacci Sequence of n (>= 0) numbers is = 0, 1, 1, 2, 3, 5, 8, 13……. Each term (other than the first two) is the sum of its immediate predecessor void fib (int n) { int a=0; b = 1; i =2; while (i<= n) do {c=a+b; a = b; b = c; i++ } } => Iterative Algorithm

Fibonacci …. Recursive Recursive Definition fib (1) = 0 fib (2) =1 fib (n) = fib(n-1) + fib(n-2) if n> 2

Contd. int binfib(int n) { if (n == 1) return 0 else if (n < 3) return 1 else return (binfib(n-1) + binfib(n-2) ) } main() {cin >> n; for (int i=1; i<= n; i++) {cout << binfib(i) << endl; }

Fibonacci …. Recursive fib (5) fib (4) fib (3) fib (2)fib (1) fib (2) fib (3) fib (2)fib (1)

Fibonacci …. Linear Recursive Input: A nonnegative integer k Output: Pair of Fibonacci numbers (Fk,Fk−1) Algorithm LFib(k) {if k ≤ 1 then return (k,0) else { (i, j) ← LFib(k−1) return (i + j, i) } }

Fibonacci …. Linear Recursive fib (7) fib (6) fib (5) fib (4) fib (3) fib (2) fib (1) (1, 0) (1, 1) (2,1) (3,2) (5,3) (8,5)

Non-linear Recursion An algorithm or function uses a number of internal recursive calls Multiple internal recursive calls are usually generated by placing a single recursive call within a loop

Non-linear Recursion General Framework Function nonlinear() {for j = k to n {perform some actions if “termination condition not met” then make a further recursive call to nonlinear() else perform some actions }

Quick Sort Fast sorting algorithm, using divide and conquer strategy Original Set of Unsorted Data Pivot All elements<= PivotAll elements > Pivot Pivot <= PivotL>PivotL<= PivotR> PivotR Pivot PivotLPivotR

Recursive QuickSort Choose a pivot value: first value, or the middle value, it can be any value, which is in range of sorted values, even if it doesn't present in the array. Partition. Rearrange elements in such a way, that all elements which are lesser than the pivot go to the left part of the array and all elements greater than the pivot, go to the right part of the array. Values equal to the pivot can stay in any part of the array. Notice, that array may be divided in non-equal parts. Sort both parts. Apply quicksort algorithm recursively to the left and the right parts.

Contd… QUICKSORT(A,p,r) { if p < r then {q = PARTITION(A,p,r) QUICKSORT(A,p,q) QUICKSORT(A,q + 1,r) }

Partitioning PARTITION(A,p,r) { x = A[p] i = p – 1 j = r + 1 while A[j] >= x j = j – 1 while A[i] < x i = i + 1 if i < j then swap A[i] A[j] return j } * This algorithm needs to be refined for handling all possible inputs.

Mutual Recursion A function calls itself indirectly via another function that calls its indirectly via the first function. Functions are interlocked together function mutual() {…..call another()….} function another() {…..call mutual()….}

Summary Using recursion can often be a useful tool for designing algorithms that have elegant, short definitions. But this usefulness does come at a modest cost. When we use a recursive algorithm to solve a problem, we have to use some of the memory locations in our computer to keep track of the state of each active recursive call. When computer memory is at a premium, then it is useful in some cases to be able to derive non-recursive algorithms from recursive ones.

References Dromey (1982), Chapter 8 on Recursive Algorithms Goodrich et.al. (2011) Chapter 3 Other Links common/readings/Recursion/index.html Fibonacci Series: Quick Sort : ap08.htm Demo of Sorting Algorithms