Recursion.

Slides:



Advertisements
Similar presentations
Recursion. Objectives At the conclusion of this lesson, students should be able to Explain what recursion is Design and write functions that use recursion.
Advertisements

Programming with Recursion
1 Chapter 18 Recursion Dale/Weems/Headington. 2 Chapter 18 Topics l Meaning of Recursion l Base Case and General Case in Recursive Function Definitions.
Recursion.
1 Chapter 7 Recursion. 2 What Is Recursion? l Recursive call A method call in which the method being called is the same as the one making the call l Direct.
CHAPTER 10 Recursion. 2 Recursive Thinking Recursion is a programming technique in which a method can call itself to solve a problem A recursive definition.
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.
1 Chapter 18-1 Recursion Dale/Weems. 2 Chapter 18 Topics l Meaning of Recursion l Base Case and General Case in Recursive Function Definitions l Writing.
1 C++ Plus Data Structures Nell Dale Chapter 7 Programming with Recursion Slides by Sylvia Sorkin, Community College of Baltimore County - Essex Campus.
1 Recursion Dr. Bernard Chen Ph.D. University of Central Arkansas.
Department of Computer Science and Engineering, HKUST 1 HKUST Summer Programming Course 2008 Recursion.
Chapter 2 Recursion: The Mirrors CS Data Structures Mehmet H Gunes Modified from authors’ slides.
Chapter 13 Recursion. Topics Simple Recursion Recursion with a Return Value Recursion with Two Base Cases Binary Search Revisited Animation Using Recursion.
Recursion A method is recursive if it makes a call to itself. A method is recursive if it makes a call to itself. For example: For example: public void.
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 11Java: an Introduction to Computer Science & Programming - Walter Savitch 1 Chapter 11 l Basics of Recursion l Programming with Recursion Recursion.
COSC 2006 Data Structures I Recursion II
1 Programming with Recursion. 2 Recursive Function Call A recursive call is a function call in which the called function is the same as the one making.
Slides prepared by Rose Williams, Binghamton University ICS201 Lecture 19 : Recursion King Fahd University of Petroleum & Minerals College of Computer.
1 Programming with Recursion Slides by Sylvia Sorkin, Community College of Baltimore County - Essex Campus and Robert Moyer, Montgomery County Community.
1 Lecture 14 Chapter 18 - Recursion. 2 Chapter 18 Topics l Meaning of Recursion l Base Case and General Case in Recursive Function Definitions l Writing.
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.
10/14/2015cosc237/recursion1 Recursion A method of defining a concept which refers to the concept itself A method of solving a problem by reducing it to.
1 C++ Plus Data Structures Nell Dale Chapter 7 Programming with Recursion Modified from the slides by Sylvia Sorkin, Community College of Baltimore County.
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.
Computer Science and Software Engineering University of Wisconsin - Platteville 9. Recursion Yan Shi CS/SE 2630 Lecture Notes Partially adopted from C++
1 C++ Plus Data Structures Nell Dale Chapter 7 Programming with Recursion Slides by Sylvia Sorkin, Community College of Baltimore County - Essex Campus.
Computer Science Department Data Structure & Algorithms Lecture 8 Recursion.
Reading – Chapter 10. Recursion The process of solving a problem by reducing it to smaller versions of itself Example: Sierpinski’s TriangleSierpinski’s.
Copyright © 2007 Pearson Education, Inc. Publishing as Pearson Addison-Wesley. Ver Recursive Solutions Recursion is an extremely powerful problem-solving.
Java Programming: Guided Learning with Early Objects Chapter 11 Recursion.
1 Recursion. 2 Chapter 15 Topics  Meaning of Recursion  Base Case and General Case in Recursive Function Definitions  Writing Recursive Functions with.
Chapter 7 Programming with Recursion. What Is Recursion? Recursive call A method call in which the method being called is the same as the one.
Pei Zheng, Michigan State University 1 Chapter 8 Recursion.
Recursion ITI 1121 N. El Kadri. Reminders about recursion In your 1 st CS course (or its equivalent), you have seen how to use recursion to solve numerical.
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.
Recursion. Objectives At the conclusion of this lesson, students should be able to Explain what recursion is Design and write functions that use recursion.
CS 116 Object Oriented Programming II Lecture 13 Acknowledgement: Contains materials provided by George Koutsogiannakis and Matt Bauer.
Recursion Powerful Tool
Programming with Recursion
Recursion Recursion is a fundamental programming technique that can provide an elegant solution certain kinds of problems © 2004 Pearson Addison-Wesley.
Recursion CENG 707.
Chapter Topics Chapter 16 discusses the following main topics:
Chapter 19: Recursion.
Recursion Version 1.0.
Recursion CENG 707.
Chapter 15 Recursion.
OBJECT ORIENTED PROGRAMMING II LECTURE 23 GEORGE KOUTSOGIANNAKIS
Recursion: The Mirrors
Recursion: The Mirrors
Analysis of Algorithms
Chapter 15 Recursion.
Recursion and Logarithms
Java 4/4/2017 Recursion.
Recursion Chapter 10.
Data Structures Recursion CIS265/506: Chapter 06 - Recursion.
Programming with Recursion
Announcements Final Exam on August 17th Wednesday at 16:00.
Applied Algorithms (Lecture 17) Recursion Fall-23
Recursion Chapter 11.
Chapter 18-3 Recursion Dale/Weems.
Basics of Recursion Programming with Recursion
Recursion Great fleas have little fleas upon their backs to bite 'em, And little fleas have lesser fleas, and so ad infinitum. And the great fleas themselves,
Recursion Great fleas have little fleas upon their backs to bite 'em, And little fleas have lesser fleas, and so ad infinitum. And the great fleas themselves,
Yan Shi CS/SE 2630 Lecture Notes
Chapter 18 Recursion.
slides created by Marty Stepp
Recursion.
Recursion: The Mirrors
Presentation transcript:

Recursion

Recursive Function Call A recursive call is a function call in which the called function is the same as the one making the call In other words, recursion occurs when a function calls itself. Avoid making an infinite sequence of function calls (infinite recursion)

Finding a Recursive Solution A recursive solution to a problem must be written carefully The idea is for each successive recursive call to bring you one step closer to a situation in which the problem can easily be solved This easily solved situation is called the base case Each recursive algorithm must have at least one base case, as well as a general (recursive) case

General format for Many Recursive Functions if (some easily-solved condition) // base case solution statement else // general case recursive function call SOME EXAMPLES . . .

Writing a recursive function to find the sum of the numbers from 1 to n DISCUSSION The function call sum(4) should have value 10, because that is 1 + 2 + 3 + 4 . For an easily-solved situation, the sum of the numbers from 1 to 1 is 1. So our base case could be along the lines of if ( n == 1 ) return 1;

Writing a recursive function to find the sum of the numbers from 1 to n Now for the general case. . . The sum of the numbers from 1 to n, that is, 1 + 2 + . . . + n can be written as n + the sum of the numbers from 1 to (n - 1), that is, n + 1 + 2 + . . . + (n - 1) or, n + sum(n - 1) And notice that the recursive call sum(n - 1) gets us “closer” to the base case of sum(1)

Finding the sum of the numbers from 1 to n public static int sum (int n) { if (n == 1) // base case return 1 ; else // general case return n + sum (n - 1) ; } 7

Trace of call for sum(4) Call 1: n 4 Call 2: Returns 2 + sum(1) n 3

Writing a recursive function to find n factorial DISCUSSION The function call fact(4) should have value 24, because that is 4 * 3 * 2 * 1 . For a situation in which the answer is known, the value of 1! is 1. So our base case could be along the lines of if ( n == 0 ) return 1;

Writing a recursive function to find n factorial Now for the general case . . . The value of factorial(n) can be written as n * the product of the numbers from (n - 1) to 1, that is, n * (n - 1) * . . . * 1 or, n * factorial(n - 1) And notice that the recursive call factorial(n - 1) gets us “closer” to the base case of factorial(1).

Recursive solution public static int factorial (int n) { if (n == 0) // base case return 1; else // general case return n * factorial (n - 1); }

Another Example: power From mathematics, we know that 20 = 1 and 25 = 2 * 24 In general, x0 = 1 and xn = x * xn-1 for integer x, and integer n > 0. Here we are defining xn recursively, in terms of xn-1

public static int power ( int x, int n) { if ( n == 0 ) // Recursive definition of power function public static int power ( int x, int n) { if ( n == 0 ) return 1; // base case else // general case return (x * power ( x , n - 1 ) ) ; } Of course, an alternative would have been to use looping instead of a recursive call in the function body. 13

Extending the definition What is the value of 2 -3 ? Again from mathematics, we know that it is 2 -3 = 1 / 23 = 1 / 8 In general, xn = 1/ x -n for non-zero x, and integer n < 0 Here we are again defining xn recursively, in terms of x-n when n < 0

// Complete recursive definition of power function public static double power (double x, int n ) { if ( n == 0 ) // base case return 1; else if ( n > 0 ) // first general case return ( x * power ( x , n - 1 ) ) ; else // second general case return ( 1.0 / power ( x , - n ) ) ; }

At times the base case can be: do nothing public static void printStars ( int n ) { if ( n <= 0 ) // base case // Do nothing else // general case { System.out.print (‘*’) ; printStars ( n - 1 ) ; } // CAN REWRITE AS . . . 16

Recursive void function public static void printStars (int n) { if (n > 0) { // general case System.out.print (‘*’) ; printStars (n - 1) ; } // base case is empty else-clause 17

Trace of call for printStars(3) * is printed Call 2: printStars(2) Call 3: printStars(1) Call 4: printStars(0) Do nothing n 3 n 2 n 1 n

Trace this function public static int f( int b, int a ) { if ( b < a ) // base case return 0 ; else // general case return ( 1 + f ( b - a , a ) ) ; } f (10, 4) = ? 19

Trace of Call for f(10, 4) Call 1: Returns 1 + f(2, 4) = 1 + 0 = 1 b a 10 4 b a 6 4 2 4 Returns 1 + f(6, 4) = 1 + 1 = 2 Call 1: f(10, 4) Returns 1 + f(2, 4) = 1 + 0 = 1 Call 2: f(6, 4) b < a Returns 0 Call 3: f(2, 4)

Writing a recursive function to print array elements in reverse order DISCUSSION For this task, we will use this method signature: public static void printRev(int [ ] data, int first, int last ); 6000 The call printRev (data, 0, 3 ); should produce this output: 95 87 36 74 74 36 87 95 data[0] data[1] data[2] data[3]

Base case and general case A base case may be a solution in terms of a “smaller” array. Certainly for an array with 0 elements, there is no more processing to do. Now our general case needs to bring us closer to the base case situation. That is, the length of the array to be processed decreases by 1 with each recursive call. By printing one element in the general case, and also processing the smaller array, we will eventually reach the situation where 0 array elements are left to be processed. In the general case, we could print either the first element, that is, data[first]. Or we could print the last element, that is, data[last]. Let’s print data[last]. After we print data[last], we still need to print the remaining elements in reverse order.

Using recursion with arrays public static int printRev(int [ ] data ,// array to be printed int first , // index of first element int last ) // index of last element { if (first <= last) { // general case System.out.print(data [ last ] + “ “) ; //print last elem printRev(data, first, last - 1); // then process the rest } // base case is empty else-clause printRev(data, 0, 2) = ? 23

printRev(data, 0, 2) Trace Call 1: Call 2: Call 3: Call 4: data[2] printed Call 2: printRev(data, 0, 1) data[1] printed Call 3: printRev(data, 0, 0) data[0] printed Call 4: printRev(data, 0, -1) Do nothing first 0 last 2 first 0 last 1 first 0 last 0 first 0 last -1

“Why use recursion?” These examples could all have been written without recursion, by using iteration instead. The iterative solution uses a loop, and the recursive solution uses an if statement. However, for certain problems the recursive solution is the most natural solution. This often occurs when structured variables are used.

Recursion with Linked Lists: revPrint(head); ‘A’ ‘B’ ‘C’ ‘D’ ‘E’ FIRST, print out this section of list, backwards THEN, print this element

Base Case and General Case A base case may be a solution in terms of a “smaller” list. Certainly for a list with 0 elements, there is no more processing to do. Our general case needs to bring us closer to the base case situation. That is, the number of list elements to be processed decreases by 1 with each recursive call. By printing one element in the general case, and also processing the smaller remaining list, we will eventually reach the situation where 0 list elements are left to be processed. In the general case, we will print the elements of the smaller remaining list in reverse order, and then print the current element.

Using recursion with a linked list public static void revPrint (NodeType head ) { if ( head != null ) { // general case revPrint (head.link) ; // process the rest // then print this element System.out.println(head.info) ; } // Base case : if the list is empty, do nothing 28

Recall that . . . Recursion occurs when a function calls itself (directly or indirectly) Recursion can be used in place of iteration (looping) Some functions can be written more easily using recursion

What is the value of f(25)? public static int f (int n) { if (n == 1) // base case return 0; else // general case return (1 + f (n / 2)); }

Trace for f(25) f(25) the original call = 1 + f(12) first recursive call = 1 + ( 1 + f(6) ) second recursive call = 1 + ( 1 + ( 1 + f(3) ) ) third recursive call = 1 + ( 1 + ( 1 + (1 + f(1) ) ) ) fourth recursive call = 1 + 1 + 1 + 1 + 0 = 4

Writing Recursive Functions There must be at least one base case, and at least one general (recursive) case--the general case should bring you “closer” to the base case. The parameter(s) in the recursive call cannot all be the same as the formal parameters in the heading, otherwise, infinite recursion would occur In function f( ), the base case occurred when (n == 1) was true--the general case brought us a step closer to the base case, because in the general case the call was to f(n/2), and the argument n/2 was closer to 1 (than n was)

// Another recursive function public static int f (int a, int b ) { int result; if ( b == 0 ) // base case result = 0; else if ( b > 0 ) // first general case result = a + f ( a , b - 1 ) ) ; else // second general case result = f ( - a , - b ) ; return result; } Trace f(5, 2) = ? Trace f(5, -3) = ? Trace f(-5, -3) = ? 33

Write a function . . . sum that takes an array a and two subscripts, low and high as arguments, and returns the sum of the elements a[low] + . . . + a[high] Write the function two ways - - using iteration and using recursion For your recursive definition’s base case, for what kind of array do you know the value of sum(a, low, high) right away?

if ( low == high ) // base case return a [low]; else // general case // Recursive definition public static int sum (int [ ] a , int low , int high ) { if ( low == high ) // base case return a [low]; else // general case return a [low] + sum( a, low + 1, high ) ; }

Write a function . . . linearSearch that takes an array a and two subscripts, low and high, and a key as arguments. Return -1 if key is not found in the elements a[low...high]. Otherwise, return the subscript where key is found Write the function two ways - - using iteration and using recursion For your recursive definition’s base case(s), for what kinds of arrays do you know the value of linearSearch(a, low, high, key) right away?

if ( a [ low ] == key ) // base case return low ; // Recursive definition public static int linearSearch(int [ ] a, int low, int high, int key) { if ( a [ low ] == key ) // base case return low ; else if ( low == high) // second base case return -1 ; else // general case return linearSearch( a, low + 1, high, key ) ; } 37

Write a function . . . binarySearch that takes a sorted array a, two subscripts, low and high, and a key as arguments. It returns -1 if key is not found in the elements a[low...high], otherwise, it returns the subscript where key is found binarySearch can also be written using iteration, or using recursion

x = binarySearch(a, 0, 14, 25 ); low high key subscripts 0 1 2 3 4 5 6 7 8 9 10 11 12 13 14 array 0 2 4 6 8 10 12 14 16 18 20 22 24 26 28 16 18 20 22 24 26 28 24 26 28 24 NOTE: denotes element examined

while ( low <= high ) { // more to examine mid = (low + high) / 2 ; // Iterative definition public static int binarySearch (int [ ] a, int low, int high, int key ) { int mid; while ( low <= high ) { // more to examine mid = (low + high) / 2 ; if ( a [ mid ] == key ) // found at mid return mid ; else if ( key < a [ mid ] ) // search left half high = mid - 1 ; else // search right half low = mid + 1 ; } return -1 ; // key not found 40

// Recursive definition public static int binarySearch (int [ ] a, int low , int high, int key ) { int mid ; if ( low > high ) // base case -- not found return -1; else { mid = (low + high) / 2 ; if ( a [ mid ] == key ) // base case-- found at mid return mid ; else if ( key < a [ mid ] ) // search left half return binarySearch ( a, low, mid - 1, key ); else // search right half return binarySearch( a, mid + 1, high, key ) ; } 41

Write a function . . . min that takes an array a and the size of the array as arguments, and returns the smallest element of the array, that is, it returns the smallest value of a[0]... a[size-1] Write the function two ways - - using iteration and using recursion For your recursive definition’s base case, for what kind of array do you know the value of min (a, size) right away?

public static int min( int [ ] a , int size ) { // Recursive definition public static int min( int [ ] a , int size ) { if ( size == 1 ) // base case return a [ 0 ] ; else { // general case int y = min ( a, size - 1 ); if ( y < a [size - 1] ) return y ; else return a [ size -1 ] ; } 43