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

Slides:



Advertisements
Similar presentations
CSC 205 Programming II Lecture 10 Towers of Hanoi.
Advertisements

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.
Chapter 10 Recursion Instructor: alkar/demirer. Copyright ©2004 Pearson Addison-Wesley. All rights reserved.10-2 Recursive Function recursive functionThe.
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.
Slides prepared by Rose Williams, Binghamton University Chapter 11 Recursion.
Recursion … just in case you didn’t love loops enough …
Slides prepared by Rose Williams, Binghamton University Chapter 11 Recursion.
Recursion. 2 CMPS 12B, UC Santa Cruz Solving problems by recursion How can you solve a complex problem? Devise a complex solution Break the complex problem.
Chapter 10 Recursion. Copyright © 2005 Pearson Addison-Wesley. All rights reserved Chapter Objectives Explain the underlying concepts of recursion.
Recursive Algorithms Nelson Padua-Perez Chau-Wen Tseng Department of Computer Science University of Maryland, College Park.
Recursion.
Chapter 11 Recursion Copyright © 2010 Pearson Addison-Wesley. All rights reserved.
Copyright © 2003 Pearson Education, Inc. Slide 1.
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.
Slides prepared by Rose Williams, Binghamton University Chapter 11 Recursion.
Recursion A recursive function is a function that calls itself either directly or indirectly through another function. The problems that can be solved.
©The McGraw-Hill Companies, Inc. Permission required for reproduction or display. 4 th Ed Chapter Chapter 15 Recursive Algorithms.
When confronted with a new problem there are two questions you should ask: 1. Is this problem like, or a special case of, a problem that I already know.
Copyright © 2009 Pearson Education, Inc. Publishing as Pearson Addison-Wesley Chapter 19: Recursion.
JAVA: An Introduction to Problem Solving & Programming, 5 th Ed. By Walter Savitch and Frank Carrano. ISBN © 2008 Pearson Education, Inc., Upper.
Chapter 11 Recursion Slides prepared by Rose Williams, Binghamton University Copyright © 2008 Pearson Addison-Wesley. All rights reserved.
Chapter 12 Recursion, Complexity, and Searching and Sorting
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.
Copyright © 2009 Pearson Education, Inc. Publishing as Pearson Addison-Wesley Java Software Solutions Foundations of Program Design Sixth Edition by Lewis.
Review Introduction to Searching External and Internal Searching Types of Searching Linear or sequential search Binary Search Algorithms for Linear Search.
Chapter 8 Recursion Modified.
Chapter 13 Recursion. Learning Objectives Recursive void Functions – Tracing recursive calls – Infinite recursion, overflows Recursive Functions that.
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(); … }
Recursion Recursion Chapter 12. Outline n What is recursion n Recursive algorithms with simple variables n Recursion and the run-time stack n Recursion.
CSIS 123A Lecture 9 Recursion Glenn Stevenson CSIS 113A MSJC.
11-1 Recursive Thinking A recursive definition is one which uses the word or concept being defined in the definition itself When defining an English word,
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.
Data Structure and Algorithms. Algorithms: efficiency and complexity Recursion Reading Algorithms.
1 Recursion Recursion is a powerful programming technique that provides elegant solutions to certain problems. Chapter 11 focuses on explaining the underlying.
© Janice Regan, CMPT 128, February CMPT 128: Introduction to Computing Science for Engineering Students Recursion.
Copyright © 2009 Pearson Education, Inc. Publishing as Pearson Addison-Wesley Chapter 12 Recursion.
Recursion Chapter 17 Instructor: Scott Kristjanson CMPT 125/125 SFU Burnaby, Fall 2013.
CS162 - Topic #10 Lecture: Recursion –The Nature of Recursion –Tracing a Recursive Function –Work through Examples of Recursion Programming Project –Discuss.
Recursion. Objectives At the conclusion of this lesson, students should be able to Explain what recursion is Design and write functions that use recursion.
chap10 Chapter 10 Recursion chap10 2 Recursive Function recursive function The recursive function is a kind of function that calls.
Function Recursion to understand recursion you must understand recursion.
Data Structures I (CPCS-204) Week # 5: Recursion Dr. Omar Batarfi Dr. Yahya Dahab Dr. Imtiaz Khan.
1 Towers of Hanoi Three pegs, one with n disks of decreasing diameter; two other pegs are empty Task: move all disks to the third peg under the following.
Lecture 11 Recursion. A recursive function is a function that calls itself either directly, or indirectly through another function; it is an alternative.
1 Data Structures CSCI 132, Spring 2016 Notes 16 Tail Recursion.
Review of Recursion What is a Recursive Method?
Recursion.
Chapter 13 Recursion Copyright © 2016 Pearson, Inc. All rights reserved.
to understand recursion you must understand recursion
Chapter 15 Recursive Algorithms
Recursive Thinking Chapter 9 introduces the technique of recursive programming. As you have seen, recursive programming involves spotting smaller occurrences.
Java Software Structures: John Lewis & Joseph Chase
to understand recursion you must understand recursion
Recursive Thinking Chapter 9 introduces the technique of recursive programming. As you have seen, recursive programming involves spotting smaller occurrences.
Recursive Definitions
Chapter 12 Recursion (methods calling themselves)
Recursion Data Structures.
Review of Recursion What is a Recursive Method?
Review of Recursion What is a Recursive Method?
Chapter 13 Recursion Copyright © 2010 Pearson Addison-Wesley. All rights reserved.
Review of Recursion What is a Recursive Method?
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); }

A classic: the Towers of Hanoi Initial situation: a stack of donut-shaped disks stacked in in order of decreasing size from bottom to top on a wooden peg Object: move all the disks to a second peg, one at a time –third peg available as temporary holding area –at no time may a larger disk be placed on top of a smaller disk

Solving towers of Hanoi Simplest case: tower of one disk -- move disk to destination peg With stack of two disks: –Move top disk to third peg –Move next disk to destination –Move disk from third peg to destination

Solving towers of Hanoi Simplest case: tower of one disk -- move disk to destination peg With stack of two disks: –Move top disk to third peg –Move next disk to destination –Move disk from third peg to destination

Solving towers of Hanoi Simplest case: tower of one disk -- move disk to destination peg With stack of two disks: –Move top disk to third peg –Move next disk to destination –Move disk from third peg to destination

Solving towers of Hanoi Simplest case: tower of one disk -- move disk to destination peg With stack of two disks: –Move top disk to third peg –Move next disk to destination –Move disk from third peg to destination

Solving towers of Hanoi Simplest case: tower of one disk -- move disk to destination peg With stack of two disks: –Move top disk to third peg –Move next disk to destination –Move disk from third peg to destination

Solving towers of Hanoi Stack of 3: –Move 2 disks from 1st peg to 3rd peg, using method already described –Move 1 disk from 1st to 2nd –Move 2 disks from 3rd to 2nd

Solving towers of Hanoi When there are two or more disks to move, always use third peg With more than two disks, we can solve the problem recursively by recognizing that the pegs are interchangeable -- that is, any peg can be used as source, destination, or “spare”

Solving towers of Hanoi In general, for a stack of n disks: –Move n-1 disks from peg 1 to peg 3 –Move 1 disk from peg 1 to peg 2 –Move n-1 disks from peg 3 to peg 2

Towers of Hanoi The top N-1 disks must be moved to peg 2, allowing you to then move the largest disk from peg 1 to peg 3. You can then move the N-1 disks from peg 2 to peg 3. Only two pegs are involved in a single move; for this, we’ll employ a helper method, moveOne

public void towersOfHanoi (int N, char from, char to, char spare) { if (N == 1) { moveOne(from, to); } else { towersOfHanoi(N-1, from, spare, to); moveOne (from, to); towersOfHanoi(N-1, spare, to, from); } private void moveOne(int from, int to) { System.out.println(from + “--->” + to); }

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

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 –in towers of Hanoi, variant expression was height -- each recursive call used height -1 as parameter threshold valueBase case is when variant expression is less than or equal to its threshold value