Recursion … just in case you didn’t love loops enough …

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

MATH 224 – Discrete Mathematics
CSE 373: Data Structures and Algorithms Lecture 5: Math Review/Asymptotic Analysis III 1.
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.
Introduction to Analysis of Algorithms
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.
Slides prepared by Rose Williams, Binghamton University Chapter 11 Recursion.
Recursion. Objectives At the conclusion of this lesson, students should be able to Explain what recursion is Design and write functions that use recursion.
Recursion … just in case you didn’t love loops enough …
Cmpt-225 Algorithm Efficiency.
Recursion.
Chapter 11 Recursion Copyright © 2010 Pearson Addison-Wesley. All rights reserved.
Copyright © 2003 Pearson Education, Inc. Slide 1.
Slides prepared by Rose Williams, Binghamton University Chapter 11 Recursion.
Main Index Contents 11 Main Index Contents Selection Sort Selection SortSelection Sort Selection Sort (3 slides) Selection Sort Alg. Selection Sort Alg.Selection.
Searching1 Searching The truth is out there.... searching2 Serial Search Brute force algorithm: examine each array item sequentially until either: –the.
Analysis of Algorithms COMP171 Fall Analysis of Algorithms / Slide 2 Introduction * What is Algorithm? n a clearly specified set of simple instructions.
CHAPTER 7: SORTING & SEARCHING Introduction to Computer Science Using Ruby (c) Ophir Frieder at al 2012.
Data Structures Introduction Phil Tayco Slide version 1.0 Jan 26, 2015.
1 C++ Plus Data Structures Nell Dale Chapter 7 Programming with Recursion Slides by Sylvia Sorkin, Community College of Baltimore County - Essex Campus.
Week 2 CS 361: Advanced Data Structures and Algorithms
Lecture 8. How to Form Recursive relations 1. Recap Asymptotic analysis helps to highlight the order of growth of functions to compare algorithms Common.
A Computer Science Tapestry 1 Recursion (Tapestry 10.1, 10.3) l Recursion is an indispensable technique in a programming language ä Allows many complex.
Chapter 13 Recursion. Topics Simple Recursion Recursion with a Return Value Recursion with Two Base Cases Binary Search Revisited Animation Using Recursion.
1 Recursion Algorithm Analysis Standard Algorithms Chapter 7.
Lecture 2 Computational Complexity
Comp 249 Programming Methodology Chapter 10 – Recursion Prof. Aiman Hanna Department of Computer Science & Software Engineering Concordia University, Montreal,
Chapter 11 Recursion Slides prepared by Rose Williams, Binghamton University Copyright © 2008 Pearson Addison-Wesley. All rights reserved.
1 Time Analysis Analyzing an algorithm = estimating the resources it requires. Time How long will it take to execute? Impossible to find exact value Depends.
COSC 2006 Data Structures I Recursion II
Chapter 12 Recursion, Complexity, and Searching and Sorting
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.
Analysis of Algorithms
Stephen P. Carl - CS 2421 Recursion Reading : Chapter 4.
Slides prepared by Rose Williams, Binghamton University ICS201 Lecture 19 : Recursion King Fahd University of Petroleum & Minerals College of Computer.
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.
Chapter 13 Recursion. Learning Objectives Recursive void Functions – Tracing recursive calls – Infinite recursion, overflows Recursive Functions that.
C++ Programming: From Problem Analysis to Program Design, Second Edition Chapter 19: Searching and Sorting.
Chapter 13 Recursion. Copyright © 2005 Pearson Addison-Wesley. All rights reserved. Slide 2 Overview Recursive Functions for Tasks(13.1) Recursive Functions.
Copyright © 2012 Pearson Addison-Wesley. All rights reserved. Chapter 14 Recursion.
CSIS 123A Lecture 9 Recursion Glenn Stevenson CSIS 113A MSJC.
CSC 211 Data Structures Lecture 13
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.
© Janice Regan, CMPT 128, February CMPT 128: Introduction to Computing Science for Engineering Students Recursion.
Winter 2006CISC121 - Prof. McLeod1 Stuff No stuff today!
C++ How to Program, 7/e © by Pearson Education, Inc. All Rights Reserved.
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.
23 February Recursion and Logarithms CSE 2011 Winter 2011.
1 Chapter 2 Algorithm Analysis Reading: Chapter 2.
Copyright © 2007 Pearson Education, Inc. Publishing as Pearson Addison-Wesley Chapter 14 Recursion.
Recursion. Objectives At the conclusion of this lesson, students should be able to Explain what recursion is Design and write functions that use recursion.
Algorithm Analysis with Big Oh ©Rick Mercer. Two Searching Algorithms  Objectives  Analyze the efficiency of algorithms  Analyze two classic algorithms.
Chapter 15 Running Time Analysis. Topics Orders of Magnitude and Big-Oh Notation Running Time Analysis of Algorithms –Counting Statements –Evaluating.
Function Recursion to understand recursion you must understand recursion.
Chapter 13 Recursion Copyright © 2016 Pearson, Inc. All rights reserved.
Recursion Version 1.0.
to understand recursion you must understand recursion
Chapter 11 Recursion Slides prepared by Rose Williams, Binghamton University Kenrick Mock, University of Alaska Anchorage Copyright © 2016 Pearson Inc.
CIS Principles of Programming
Chapter 14 Recursion. Chapter 14 Recursion Overview 14.1 Recursive Functions for Tasks 14.2 Recursive Functions for Values 14.3 Thinking Recursively.
to understand recursion you must understand recursion
Algorithm An algorithm is a finite set of steps required to solve a problem. An algorithm must have following properties: Input: An algorithm must have.
Analyzing an Algorithm Computing the Order of Magnitude Big O Notation
Chapter 13 Recursion Copyright © 2010 Pearson Addison-Wesley. All rights reserved.
Presentation transcript:

Recursion … just in case you didn’t love loops enough …

Recursion A recursive method is a method that contains a call to itself Often used as an alternative to iteration when iteration is awkward or “inelegant” Each recursive call is given a smaller portion of the original problem Last recursive call solves diminished problem without recursion

Example // method writes digits of a non-negative number, stacked vertically public void write_vertical(int n) { n = Math.abs(n); if (n < 10) System.out.println(“” + n); else { write_vertical(n / 10); System.out.println(“” + n % 10); }

Tracing recursive method write_vertical 1. write_vertical(52406); n=52406 n/10= write_vertical(n/10) ; n=5240 n/10= write_vertical(n/10); n=524 n/10=52 4. write_vertical(n/10); n=52 n/10=5 5. write_vertical(n/10); n=5 Stop recursion! Output: 6. System.out.println(“” + n); System.out.println (“” + n%10); 8. System.out.println (“” + n%10); 9. System.out.println(n%10); 10. System.out.println (“” + n%10);

Elements of recursive method Base caseBase case: problem is simplified to the point where recursion becomes unnecessary: n < 10 Variant expressionVariant expression: the part of the problem that changes, making the problem smaller: n Recursive callRecursive call: method calls itself: write_vertical (n / 10);

How recursion works Activation record: memory block that stores all the information a method needs to work: –values of local variables & parameters –where method should return to (so calling method can resume execution)

How recursion works When a method call is encountered, execution of current method ceases Information for newly called method is stored in an activation record Method executes

How recursion works If new method contains another method call, the process just described repeats Each recursive call generates its own activation record –as each recursive call is encountered, previous activation record is stored on run-time stack –when last call fails to generate a new activation record, stacked calls are removed (in reverse of the order they were stored), and each process continues in succession

Remember, for a recursive method to be successful... Must be a problem with one or more cases in which some subtasks are simpler versions of the original problem - use recursion for these Must also have one or more cases in which entire computation is accomplished without recursion (base case)

Another example: the powers method Suppose you wanted to find the value of X n For most values of n, we can solve this iteratively using a simple loop: int answer = 1; for (int c = 1; c <= n; c++) answer *= X; We can take care of the cases of n=1 or n=0 with simple if statements; but what about a negative value of n?

Finding a recursive solution We can observe that for any value of n, X n is equal to X * X (n-1) Armed with this information, we can easily develop a recursive solution that covers all values of X and n

Recursive power method double rpower (double X, int n) { if (X == 0) return 0; else if (n == 0) return 1; else if (n > 0) return X * rpower(X, n-1); else // n < 0 return 1 / rpower(X, -n); }

Drawing pictures with recursion We used ASCII art to illustrate how iteration worked – we can do the same with recursion For example, if we wanted to draw a line using several instances of a single character, we could write a loop like the one below: for (int x = lineLen; x > 0; x--) System.out.print(“$ ”); We can do the same task recursively; see next slide

Example public void drawLine (int x) { if (x == 0) return; System.out.print(“$”); drawLine(x-1); }

Same example, slightly different The original iterative line drawing routine was different from typical examples we’ve seen in the past, in that the counter was counting down instead of up I did this to illustrate how the iterative version relates to the recursive version – the problem (value of counter) gets smaller with each loop iteration, or each recursive call The situation is the same if we have the counter counting up, but it’s a little harder to see

Example Iterative version: for (int x = 0; x < someConstant; x++) System.out.print (“$ ”); Equivalent recursive version: public drawLine (int x, int someConstant) { if (x < someConstant) { System.out.print(“$”); drawLine (x+1, someConstant); } distance between Instead of x getting smaller, the distance between x and someConstant gets smaller

Drawing prettier pictures: random Fractals Fractals are mathematical phenomena that describe the kinds of seemingly random shapes that occur in nature Graphics programmers use fractals to draw natural-looking scenes Your textbook (as paraphrased on the next slide) describes one method for generating random fractals

Fractals made simple 1. Start with a line; find its midpoint: 2. Bend the line at the midpoint, using a random angle: 3. Lather, rinse, repeat:

An applet for fractals When we draw the lines that make up a fractal, we continually perform 3 tasks: –find the midpoint of a line –randomly generate a distance –draw two new lines, which stretch from a point the generated distance above the midpoint to the points at the two ends of the original line

An applet for fractals We keep performing the three tasks described, breaking the original line into smaller and smaller segments until some end state is reached If we think of the end state as being the minimum distance we want to allow between any two points (or the minimum length of a line segment), we can come up with a recursive solution that starts with the original line length and stops when we have reached the minimum for each segment

The heart of the matter: the randomFractal method public void randomFractal( int leftX, int leftY, int rightX, int rightY, Graphics drawingArea) { final int STOP = 4; // When length < EPSILON, draw a line segment int midX, midY; // Midpoints in the x and y dimensions int delta; // Amount to shift the line's midpoint up or down if ((rightX - leftX) <= STOP) drawingArea.drawLine(leftX, leftY, rightX, rightY); else { midX = (leftX + rightX) / 2; midY = (leftY + rightY) / 2; delta = rg.nextInt(rightX - leftX); midY += delta; randomFractal(leftX, leftY, midX, midY, drawingArea); randomFractal(midX, midY, rightX, rightY, drawingArea); } }

Searching an array We have discussed the problem of searching for a value within an array With unsorted data, our only real option is to start at one end of the array and search until we either find the target value or exhaust all of the possibilities The method on the next slide illustrates such a process

Serial search – the brute force way public int serialSearch(int n) { for (int x = 0; x < size; x++) if (array[x] == n) return x; return -1; } Worst case, this method is O(n)

A recursive search method A more efficient search method can be defined recursively, and is somewhat analogous to the random fractal example: –check value at midpoint; if not target then –if greater than target, make recursive call to search “upper” half of structure –if less than target, recursively search “lower” half Works only if data are sorted

Binary search code public int binarySearch(int n, int first, int extent) { int mid = extent/2; if (extent == 0) return -1; else { if (array[mid] n) binarySearch(n, mid+1, (extent-1)/2); return mid; } }

searching26 Binary search in action Suppose you have a 13-member array of sorted numbers: [0] [1] [2] [3] [4] [5] [6] [7] [8] [9] [10] [11] [12] Searching for value: 113 Initial function call:first = 0, extent = 13, mid = 6

searching27 Binary search in action Searching for value: 113 Initial function call:first = 0, extent = 13, mid = 6 Since 113 != 82, make recursive call: binarySearch (target, mid+1, (extent-1)/2); [0] [1] [2] [3] [4] [5] [6] [7] [8] [9] [10] [11] [12]

searching28 Binary search in action Searching for value: 113 Recursive call(1):first = 7, extent = 6, mid = 10 [0] [1] [2] [3] [4] [5] [6] [7] [8] [9] [10] [11] [12]

searching29 Binary search in action Searching for value: 113 Recursive call(1):first = 7, extent = 6, mid = 10 Since 113 != 130, make recursive call: binarySearch(target, first, extent/2); [0] [1] [2] [3] [4] [5] [6] [7] [8] [9] [10] [11] [12]

searching30 Binary search in action Searching for value: 113 Recursive call(2):first = 7, extent = 3, mid = 8 [0] [1] [2] [3] [4] [5] [6] [7] [8] [9] [10] [11] [12]

searching31 Binary search in action Searching for value: 113 Recursive call(2):first = 7, extent = 3, mid = 8 Since 113 != 108, make recursive call: binarySearch(target, mid+1, (extent-1)/2); [0] [1] [2] [3] [4] [5] [6] [7] [8] [9] [10] [11] [12]

searching32 Binary search in action Searching for value: 113 Recursive call(3):first = 9, extent = 1, mid = 9 [0] [1] [2] [3] [4] [5] [6] [7] [8] [9] [10] [11] [12]

searching33 Binary search in action Searching for value: 113 Recursive call(3):first = 9, extent = 1, mid = 9 Since 113 == 113, target is found; found = true, location = 9 [0] [1] [2] [3] [4] [5] [6] [7] [8] [9] [10] [11] [12]

searching34 Binary Search Analysis Worst-case scenario: item is not in the array –algorithm keeps searching smaller subarrays –eventually, array size will be 0, and the search will stop Analysis requires computing time needed for operations in function as well as amount of time for recursive calls We will analyze the algorithm’s performance in the worst case

searching35 Step 1: count operations Test base case: if (extent==0) 1 operation Compute midpoint: mid = first + extent/2; 3 operations Test for target at midpoint: if (target == array[mid])2 operations Test for which recursive call to make: if (target < array[mid])2 operations Recursive call - requires some arithmetic and argument passing - estimate 10 operations

searching36 Step 2: analyze cost of recursion Each recursive call is preceded by 18 (or fewer) operations Multiply this number by the depth of recursive calls and add the number of operations performed in the stopping case to determine worst-case running time (T(n)) T(n) = 18 * depth of recursion + 3

searching37 Step 3: estimate depth of recursion Calculate upper bound approximation for depth of recursion; may slightly overestimate, but will not underestimate actual value –Each recursive call is made on an array segment that contains, at most, N/2 elements –Subsequent calls are always made on size/2 –Thus, depth of recursion is, at most, the number of times N can be divided by 2 with a result > 1

searching38 Estimating depth of recursion Referring to “the number of times N is divisible by 2 with result > 1” as H(n), or the halving function, the time expression becomes: T(n) = 18 * H(n) + 3 H(n) turns out to be almost exactly equal to log 2 n: H(n) = log 2 n meaning that fractional results are rounded down to the nearest whole number (e.g. 3.7 = 3) -- this notation is called the floor function

searching39 Worst-case time for binary search Substituting the floor function of the logarithm for H(n), the time expression becomes: T(n) = 18 * ( log 2 n ) + 3 Throwing out the constants, the worst- case running time (big O) function is: O(log n)

searching40 Significance of logarithms Logarithmic algorithms are very fast because log n is much smaller than n The larger the data set, the more dramatic the difference becomes: –log 2 8 = 3 –log 2 64 = 6 –log < 10 –log 2 1,000,000 < 20

searching41 For binary search algorithm... To search a 1000 element array will require no more than 183 operations in the worst case To search a 1,000,000 element array will require less than 400 operations in the worst case

When Not to Use Recursion When recursive algorithms are designed carelessly, it can lead to very inefficient and unacceptable solutions In general, use recursion if –A recursive solution is natural and easy to understand. –A recursive solution does not result in excessive duplicate computation. –The equivalent iterative solution is too complex.

Preventing infinite recursion One-level recursion: every case is either a stopping case or makes a recursive call to a stopping case Since most recursive functions are, or have the potential to be, recursive beyond just one level, need more general method for determining whether or not recursion will stop

Preventing infinite recursion variant expressionDefine a variant expression –numeric quantity that decreases by a fixed amount on each recursive call threshold valueBase case is when variant expression is less than or equal to its threshold value