CS 116 Object Oriented Programming II Lecture 13 Acknowledgement: Contains materials provided by George Koutsogiannakis and Matt Bauer.

Slides:



Advertisements
Similar presentations
Starting Out with Java: From Control Structures through Objects
Advertisements

Lecture 12 Recursion part 1
Recursion.
1 Chapter 11 l Basics of Recursion l Programming with Recursion Recursion.
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 Chapter 7. Spring 2010CS 2252 Chapter Objectives To understand how to think recursively To learn how to trace a recursive method To learn how.
Recursion. Binary search example postponed to end of lecture.
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.
Fall 2007CS 2251 Recursion Chapter 7. Fall 2007CS 2252 Chapter Objectives To understand how to think recursively To learn how to trace a recursive method.
Chapter 19 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.
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 Chapter 7. Chapter 7: Recursion2 Chapter Objectives To understand how to think recursively To learn how to trace a recursive method To learn.
Copyright © 2008 Pearson Education, Inc. Publishing as Pearson Addison-Wesley Starting Out with Java: Early Objects Third Edition by Tony Gaddis Chapter.
Recursion Chapter 7. Chapter 7: Recursion2 Chapter Objectives To understand how to think recursively To learn how to trace a recursive method To learn.
CS212: DATASTRUCTURES Lecture 3: Recursion 1. Lecture Contents 2  The Concept of Recursion  Why recursion?  Factorial – A case study  Content of a.
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.
Copyright © 2009 Pearson Education, Inc. Publishing as Pearson Addison-Wesley Chapter 19: Recursion.
1 C++ Plus Data Structures Nell Dale Chapter 7 Programming with Recursion Slides by Sylvia Sorkin, Community College of Baltimore County - Essex Campus.
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,
Chapter 14: Recursion Starting Out with C++ Early Objects
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.
1 Decrease-and-Conquer Approach Lecture 06 ITS033 – Programming & Algorithms Asst. Prof. Dr. Bunyarit Uyyanonvara IT Program, Image and Vision Computing.
Recursion Chapter 7. Chapter Objectives  To understand how to think recursively  To learn how to trace a recursive method  To learn how to write recursive.
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.
15-1 Chapter-18: Recursive Methods –Introduction to Recursion –Solving Problems with Recursion –Examples of Recursive Methods.
Copyright © 2015 Pearson Education, Inc. Publishing as Pearson Addison-Wesley C H A P T E R 12 Recursion.
Copyright © 2010 Pearson Education, Inc. Publishing as Pearson Addison-Wesley Starting Out with Programming Logic & Design Second Edition by Tony Gaddis.
Chapter 12 Recursion, Complexity, and Searching and Sorting
Recursion Chapter 11. The Basics of Recursion: Outline Introduction to Recursion How Recursion Works Recursion versus Iteration Recursive Methods That.
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.
Lecturer: Dr. AJ Bieszczad Chapter 11 COMP 150: Introduction to Object-Oriented Programming 11-1 l Basics of Recursion l Programming with Recursion Recursion.
Slides prepared by Rose Williams, Binghamton University ICS201 Lecture 19 : Recursion King Fahd University of Petroleum & Minerals College of Computer.
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.
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.
Copyright © 2010 Pearson Education, Inc. Publishing as Pearson Addison-Wesley Starting Out with Programming Logic & Design Second Edition by Tony Gaddis.
Reading – Chapter 10. Recursion The process of solving a problem by reducing it to smaller versions of itself Example: Sierpinski’s TriangleSierpinski’s.
CS212: DATASTRUCTURES Lecture 3: Recursion 1. Lecture Contents 2  The Concept of Recursion  Why recursion?  Factorial – A case study  Content of a.
Review Introduction to Searching External and Internal Searching Types of Searching Linear or sequential search Binary Search Algorithms for Linear Search.
Advanced Computer Architecture and Parallel Processing Rabie A. Ramadan http:
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.
Java Programming: Guided Learning with Early Objects Chapter 11 Recursion.
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.
CS 116 OBJECT ORIENTED PROGRAMMING II LECTURE 12 GEORGE KOUTSOGIANNAKIS Copyright: 2015 Illinois Institute of Technology/ George Koutsogiannakis 1.
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.
1. Searching The basic characteristics of any searching algorithm is that searching should be efficient, it should have less number of computations involved.
1 Recursive algorithms Recursive solution: solve a smaller version of the problem and combine the smaller solutions. Example: to find the largest element.
CS 116 Object Oriented Programming II Lecture 4 Acknowledgement: Contains materials provided by George Koutsogiannakis and Matt Bauer.
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! =
Chapter 15 Running Time Analysis. Topics Orders of Magnitude and Big-Oh Notation Running Time Analysis of Algorithms –Counting Statements –Evaluating.
Recursion.
Chapter Topics Chapter 16 discusses the following main topics:
Chapter 15 Recursion.
OBJECT ORIENTED PROGRAMMING II LECTURE 23 GEORGE KOUTSOGIANNAKIS
Chapter 15 Recursion.
Recursion "To understand recursion, one must first understand recursion." -Stephen Hawking.
Chapter 18 Recursion.
Dr. Sampath Jayarathna Cal Poly Pomona
Presentation transcript:

CS 116 Object Oriented Programming II Lecture 13 Acknowledgement: Contains materials provided by George Koutsogiannakis and Matt Bauer

Topics Recursion

Sometimes large problems can be solved by transforming the large problem into smaller and smaller problems until you reach an easily solved problem. This methodology of successive reduction of problems is called Recursion. That easy-to-solve sub-problem is called the base case(s). The formula that reduces the size of a problem is called the general case. 3

Recursive Methods Recursive call: A method call in which the method being called is the same as the one making the call In other words, recursion occurs when a method calls itself! The arguments passed to the recursive call are smaller in value than the original arguments. Infinite recursion An infinite sequence of recursive method calls (not good) 4

Recursion When designing a recursive solution for a problem, we need to do the following: Define the base case(s) Define the rule for the general case 5 if (condition where solution is known) // Base case(s) solution statement else // General case recursive method call

Problems with the Recursion Structure The sum of the numbers from 1 to n, that is, n, can be written as n + the sum of the numbers from 1 to (n - 1), that is, n (n - 1) or, n + summation(n - 1) And notice that the recursive call summation(n - 1) gets us “closer” to the base case of summation(1)

Series Summation The method call summation(4) should return the value 10, because that is the result of A situation where the answer is known is when n is 1: The sum of the numbers from 1 to 1 is certainly just 1. So our base case could be along the lines of if ( n == 1 ) return 1;

Series Summation cont. public static int summation(int n) { // Returns sum of numbers from 1 to n // Assumption: n is greater than 0 // Computes sum of the numbers from 1 to n by // adding n to the sum of the numbers from 1 to // (n-1) if (n == 1) // Base case return 1; else // General case return (n + summation(n - 1)); }

Series Summation cont.

Another Example: Power Function

// Recursive definition of power function public static int power (int x, int n) // Assumptions: n greater than or equal to 0. // x and n are not both zero // Returns x raised to the power n. { if (n == 0) return 1; // Base case else // General case return (x * power (x, n-1)); }

Calculating a Factorial The factorial of a positive number is defined as factorial( n ) = n! = n * ( n – 1 ) * ( n – 2 ) * … 3 * 2 * 1 By convention, factorial( 0 ) = 0! = 1 (The factorial of a negative number is not defined.) Can we find a relationship between the problem at hand and a smaller, similar problem? 12

Calculating a Factorial factorial( n ) = n * factorial( n – 1 ) At each step, the size of the problem is reduced by 1: we progress from a problem of size n to a problem of size (n – 1) A call to factorial( n ) will generate a call to factorial( n – 1 ), which in turn will generate a call to factorial( n – 2 ), …. Eventually, a call to factorial( 0 ) will be generated; this is our easy-to-solve problem. We know that factorial( 0 ) = 1. That is the base case. 13

Code for a Recursive Factorial Method public static int factorial( int n ) { if ( n <= 0 ) // base case return 1; else // general case return ( n * factorial( n – 1 ) ); } See Example 13.2 RecursiveFactorial.java 14

In coding a recursive method, failure to code the base case will result in a run-time error. If the base case is not coded, when the method is called, the recursive calls keep being made because the base case is never reached. This eventually generates a StackOverflowError. 15 Common Error Trap

Greatest Common Divisor The Greatest Common Divisor (gcd) of two positive integer numbers is the greatest positive integer that divides evenly into both numbers. The Euclidian algorithm finds the gcd of two positive integers a and b. It is based on the fact that: gcd(a,b) = gcd (b,a%b), b<=a 16 Remainder of (a/b)

GCD Example: Euclidian Algorithm If a = and b = 60378, then … % = 2694 (different from 0) % 2694 = 1110 (different from 0) 2694 % 1110 = 474 (different from 0) 1110 % 474 = 162 (different from 0) 474 % 162 = 150 (different from 0) 162 % 150 = 12 (different from 0) 150 % 12 = 6 (different from 0) 12 % 6 = 0  gcd( , ) = 6 17 Remainder of /60378

Recursion in Arrays In Class Practice: Print items in reverse order Reverse order of: Print: 11 (last item of array) Reverse order of: Print: 1 (last item of array) Print: 82 (last item of array) Reverse order of: Print: 67 (last item of array)

In Class Practice What is the base case? What is the general case?

Does Binary Search have a recursive structure?

Value Index Key 23 Start= 0 End=8 Mid=(Start+End)/2=4 Is Array[Mid]==Key? Start= 0 End=3 Mid=(Start+End)/2=1 Is Array[Mid]==Key? Binary Search Example 1 (Key in array)

Value Index Key 56 Start= 0 End=8 Mid=(Start+End)/2=4 Is Array[Mid]==Key? Start=0 End=3 Mid=(Start+End)/2=1 Is Array[Mid]==Key? Binary Search Example 2 (Key in array) Start=2 End=3 Mid=(Start+End)/2=2 Is Array[Mid]==Key? Start=3 End=3 Mid=(Start+End)/2=3 Is Array[Mid]==Key?

Value Index Key 58 Start= 0 End=8 Mid=(Start+End)/2=4 Is Array[Mid]==Key? Start=0 End=3 Mid=(Start+End)/2=1 Is Array[Mid]==Key? Binary Search Example 3 (Key not in array) Start=2 End=3 Mid=(Start+End)/2=2 Is Array[Mid]==Key? Start=3 End=3 Mid=(Start+End)/2=3 Is Array[Mid]==Key?

How many and what parameters does our recursive binary search method take? Our non-recursive method, in Chapter 8, took only two parameters: the array and the search key. The subarray being searched is defined inside the method by two local variables, start and end, representing the indexes of the first and last elements of the subarray. 24 Recursive Binary Search Example 2

When we make a recursive call to search the left or the right subarray, our recursive call will define the subarray that we search. Thus, our recursive Binary Search method will have two extra parameters, representing the indexes of the first and last elements of the subarray to search. 25 Recursive Binary Search Example 2

public int recursiveBinarySearch ( int [] arr, int key, int start, int end ) { if ( start <= end ) { int middle = ( start + end ) / 2; if ( arr[middle] == key ) // key found return middle; // base case #1 else if ( arr[middle] > key ) // look left return recursiveBinarySearch(arr, key, start, middle – 1 ); else // look right return recursiveBinarySearch(arr, key, middle + 1, end ); } else// key not found return -1; // base case #2 } 26 Recursive Binary Search Code

Recursive Binary Search (More detailed Slides) Our Recursive Binary Search will implement a Binary Search using recursion. Review: A Binary Search searches a sorted array for a search key value. We assume the array is sorted in ascending order. If the search key is found, we return the index of the element with that value. If the search key is not found, we return

We begin by comparing the middle element of the array with the search key. If they are equal, we have found the search key and return the index of the middle element. This is a base case. 28 Recursive Binary Search

If the middle element’s value is greater than the search key, then the search key cannot be found in elements with higher array indexes. So, we continue our search in the left half of the array. If the middle element’s value is less than the search key, then the search key cannot be found in elements with lower array indexes lower. So, we continue our search in the right half of the array. 29 Recursive Binary Search

Searching the left or right subarray is made via a recursive call to our Binary Search method. We pass the subarray to search as an argument. Since the subarray is smaller than the original array, we have progressed from a bigger problem to a smaller problem. That is our general case. If the subarray to search is empty, we will not find our search key in the subarray, and we return –1. That is another base case. 30 Recursive Binary Search

For example, we will search for the value 7 in this sorted array: To begin, we find the index of the center element, which is 8, and we compare our search key (7) with the value Recursive Binary Search

A recursive call is made to search the left subarray, comprised of the array elements with indexes between 0 and 7 included. The index of the center element is now 3, so we compare 7 to the value Recursive Binary Search

A recursive call is made to search the left subarray, comprised of the array elements with indexes between 0 and 2 included. The index of the center element is now 1, so we compare 7 to the value Recursive Binary Search

A recursive call is made to search the right subarray, comprised of the only array element with index between 2 and 2 included. The value of the element at index 2 matches the search key, so we have reached a base case and we return the index 2 (successful search). 34 Recursive Binary Search

Recursive Binary Search Example 2 This time, we search for a value not found in the array, 34. Again, we start with the entire array and find the index of the middle element, which is 8. We compare our search key (34) with the value

A recursive call is made to search the left subarray, comprised of the array elements with indexes between 0 and 7 included. The index of the center element is now 3, so we compare 34 to the value Recursive Binary Search Example 2

A recursive call is made to search the right subarray, comprised of the array elements with indexes between 4 and 7 included. The index of the center element is now 5, so we compare 34 to the value Recursive Binary Search Example 2

A recursive call is made to search the right subarray, comprised of the array elements with indexes between 6 and 7 included. The index of the center element is now 6, so we compare 34 to the value Recursive Binary Search Example 2

A recursive call is made to search the right subarray, comprised of the only array element with index between 7 and 7 included. The index of the center (only) element is now 7, so we compare 34 to the value 36. A recursive call is made to search the left subarray, but that left subarray is empty. We have reached the other base case, and we return –1, indicating an unsuccessful search. 39 Recursive Binary Search Example 2

How many and what parameters does our recursive binary search method take? Our non-recursive method, in Chapter 8, took only two parameters: the array and the search key. The subarray being searched is defined inside the method by two local variables, start and end, representing the indexes of the first and last elements of the subarray. 40 Recursive Binary Search Example 2

When we make a recursive call to search the left or the right subarray, our recursive call will define the subarray that we search. Thus, our recursive Binary Search method will have two extra parameters, representing the indexes of the first and last elements of the subarray to search. 41 Recursive Binary Search Example 2

Recursion Versus Iteration A recursive method is implemented using decision constructs (if/else statements) and calls itself. An iterative method is implemented with looping constructs (while or for statements) and repeatedly executes the loop. Printing “Hello World” n times and calculating a factorial can easily be coded using iteration. Other problems, such as the Towers of Hanoi and Binary Search, are more easily coded using recursion. 42

Recursion Versus Iteration Considerations when deciding to use recursion or iteration include: Efficiency of the method at execution time: often, recursion is slower due to overhead associated with method calls. Readability and maintenance: often, a recursive formulation is easier to read and understand than its iterative equivalent. 43