Recursion You may have seen mathematical functions defined using recursion Factorial(x) = 1 if x <= 1 = Factorial(x-1) * x otherwise Recursion means that.

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

Factorial Recursion stack Binary Search Towers of Hanoi
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.
1 CSCD 300 Data Structures Recursion. 2 Proof by Induction Introduction only - topic will be covered in detail in CS 320 Prove: N   i = N ( N + 1.
Chapter 2 Recursion: The Mirrors. © 2005 Pearson Addison-Wesley. All rights reserved2-2 Recursive Solutions Recursion is an extremely powerful problem-solving.
Chapter 19 Recursion.
Review of Recursion What is a Recursive Method? The need for Auxiliary (or Helper) Methods How Recursive Methods work Tracing of Recursive Methods.
Recursion. Recursive Solutions Recursion breaks a problem into smaller identical problems – mirror images so to speak. By continuing to do this, eventually.
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.
© 2006 Pearson Addison-Wesley. All rights reserved3-1 Chapter 3 Recursion: The Mirrors.
Chapter 2 Recursion: The Mirrors. © 2005 Pearson Addison-Wesley. All rights reserved2-2 Recursive Solutions Recursion is an extremely powerful problem-
© 2006 Pearson Addison-Wesley. All rights reserved 3-1 Chapter 3 Recursion: The Mirrors.
Chapter 3 Recursion: The Mirrors. © 2004 Pearson Addison-Wesley. All rights reserved 3-2 Recursive Solutions Recursion –An extremely powerful problem-solving.
1 Recursion Algorithm Analysis Standard Algorithms Chapter 7.
Chapter 9: Recursion1 CHAPTER 9 RECURSION. Recursion  Concept of recursion  A recursive: Benefit and Cost  Comparison : Iterative and recursive functions.
Slides prepared by Rose Williams, Binghamton University ICS201 Lecture 19 : Recursion King Fahd University of Petroleum & Minerals College of Computer.
Review Introduction to Searching External and Internal Searching Types of Searching Linear or sequential search Binary Search Algorithms for Linear Search.
Recursion Recursion Chapter 12. Outline n What is recursion n Recursive algorithms with simple variables n Recursion and the run-time stack n Recursion.
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.
1 CompSci 105 SS 2005 Principles of Computer Science Lecture 6: Recursion Lecturer: Santokh Singh Assignment 1 due tomorrow. Should have started working.
©TheMcGraw-Hill Companies, Inc. Permission required for reproduction or display. Chapter 15 * Recursive Algorithms.
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.
Programming With Java ICS201 University Of Ha’il1 Chapter 11 Recursion.
1 Recursive algorithms Recursive solution: solve a smaller version of the problem and combine the smaller solutions. Example: to find the largest element.
Lecture 11 Recursion. A recursive function is a function that calls itself either directly, or indirectly through another function; it is an alternative.
Chapter 9 Recursion. Copyright ©2004 Pearson Addison-Wesley. All rights reserved.10-2 Recursive Function recursive functionThe recursive function is –a.
Recursion.
Chapter 18 Recursion CS1: Java Programming Colorado State University
Review of Recursion What is a Recursive Method?
Chapter 14 Recursion.
Recursion CENG 707.
Chapter Topics Chapter 16 discusses the following main topics:
Chapter 19: Recursion.
Recursion Version 1.0.
Recursion CENG 707.
Recursion what is it? how to build recursive algorithms
Chapter 15 Recursion.
Chapter 10 Recursion Instructor: Yuksel / Demirer.
Recursion (Part 2).
OBJECT ORIENTED PROGRAMMING II LECTURE 23 GEORGE KOUTSOGIANNAKIS
Recursion: The Mirrors
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.
Towers of Hanoi Move n (4) disks from pole A to pole C
Chapter 15 Recursion.
Chapter 19 Recursion.
Chapter 14: Recursion Starting Out with C++ Early Objects
Recursion CSE 2320 – Algorithms and Data Structures
Recursive Thinking Chapter 9 introduces the technique of recursive programming. As you have seen, recursive programming involves spotting smaller occurrences.
Announcements Final Exam on August 17th Wednesday at 16:00.
Recursion "To understand recursion, one must first understand recursion." -Stephen Hawking.
Recursion: The Mirrors
Algorithm design and Analysis
Recursion Data Structures.
Recursion.
Recursion Chapter 18.
7.Recursion Recursion is the name given for expression anything in terms of itself. Recursive function is a function which calls itself until a particular.
Review of Recursion What is a Recursive Method?
Recursion Definition: A method that calls itself. Examples
Recursion: The Mirrors
Chapter 17 Recursion.
Recursion: The Mirrors
Review of Recursion What is a Recursive Method?
Chapter 3 :Recursion © 2011 Pearson Addison-Wesley. All rights reserved.
Recursion Chapter 12.
Review of Recursion What is a Recursive Method?
Recursion: The Mirrors
Presentation transcript:

Recursion You may have seen mathematical functions defined using recursion Factorial(x) = 1 if x <= 1 = Factorial(x-1) * x otherwise Recursion means that the definition for a function is defined with reference to itself In programming, recursion calls for writing a method that calls itself with a “smaller” set of data In the case of factorial above, each recursive call is with a small value of x Upon x reaching 1 (or smaller), recursion ends – this condition is known as the base case Recursion is often a challenging topic for programmers Its hard to think recursively Its hard to debug recursive code So why use it? Because there are some problems that must be solved recursively and others that actually are easy to solve recursively

Some Recursive methods Call factorial with int f = factorial(n); Call fibonacci with int fib = fibonacci(x); Call search with int index = search(a, n, t, 0); Call count with int count = search(a, n, t, 0); public int factorial(int x) { if(x<=1) return 1; else return x * factorial(x-1); } public int fibonacci(int x) { if(x<=0) return 0; else if(x<=2) return 1; else return fibonacci(x-1) + fibonacci(x-2); public int search(int[] array, int n, int target, int i) { if(i>=n) return -1; // not found else if(array[i]==target) return i; else return search(array, n, target, i+1); public int count(int[] array, int n, int target, int i) { if(i>=n) return 0; else if(array[i]==target) return count(array, n, target, i+1) + 1; else return count(array, n, target, i+1);

Why Recursion Works We rely on temporary values stored on the run-time stack To the right we see how the stack changes for factorial(4)

Recursion vs Iteration We can solve the previous problems with iteration In fact, many problems can be solved either iteratively or recursively With iteration, we need extra local variables, for instance to store loop variables With recursion, the code is more concise Some would call the recursive approach more “elegant” The recursive solution is easy if you can define the function recursively Note that not all problems solved through recursion are considered “functions” – they don’t necessarily return a computed value (search for instance would not really be thought of as a mathematical function) Why use iteration? Recursion comes at a cost – every method call requires using the run-time stack in memory which is slower than references local variables most likely stored in registers

Recursive vs Iterative Palindrome Checker Given a String, test to see if it is a palindrome (same backward as forward) Iteratively – loop starting at char 0 until you reach the halfway point, comparing each character against the opposite character at the other half of the String, immediately stop if you find a mismatch Recursively – compare the current character to the character on the opposite side of the String and if not equal, return false, otherwise recursively call the method incrementing the index pointing at the character, if you reach the midpoint, return true public boolean iterativePalindrome(String s) { for(int i=0;i<s.length();i++) if(s.charAt(i)!=s.charAt(s.length()-i-1) return false; return true; } public boolean recursivePalindrome(String s, int i) { if(i>s.length()/2) return true; else if(s.charAt(i)!=s.charAt(s.length()-i-1)) return false; else return recursivePalindrom(s, i+1);

Recursive vs Iterate Reverse String Methods Three approaches to reverse a String (two recursively, one iteratively) the first recursive version uses an index passed to the method to indicate which character to output while the second uses substring to continually chop the front character off the String public static String reverse1(String s, int i) { if(i==s.length()) return ""; else return reverse1(s, i+1)+s.charAt(i); } public static String reverse2(String s) { if(s.length()==0) return ""; else return reverse2(s.substring(1,s.length()))+s.charAt(0); public static String reverse3(String s) { String temp=“”; for(int i=s.length()-1;i>=0;i--) temp+= s.charAt(i); return temp;

Recursive Binary Search Binary search is often cited as an excellent algorithm to implement recursively Our base case is that we either have found the item at mid, or low > high and the item does not exist in the array Otherwise, if the value at mid < target, call binary search with the value of low set to mid+1 Otherwise call binary search with the value of high set to mid-1 public int binarySearch(int[] a, int low, int high, int target) { if(low > high) return -1; else { int mid = (low+high)/2; if(a[mid]==target) return mid; else if(a[mid]<target) return binarySearch(a, mid+1, high, target); else return binarySearch(a, low, mid-1, target); }

Problems Not (easily) Solvable by Iteration The main reason to use recursion is that there are many problems not easily solvable using loops Towers of Hanoi Generating fractal images (see right and below) Some search algorithms (mergesort, quicksort) Search problems (8 queens, Knight’s tour, Knapsack)

Towers of Hanoi A historic problem (possibly developed by monks in what is now Vietnam) Given 3 “towers” (spikes) and n disks where each disk is smaller than the one it sits on Move all disks, one at a time, from tower 1 to tower 3 such that you never place a larger disk on a smaller disk What pattern of movements can we take to solve the problem? Using iteration is challenging, but the recursive solution is almost trivially simple

Towers of Hanoi Solution public static void hanoi(int n, int a, int b, int c) { if(n==1) System.out.println(“Move disk “ + n + “ from “ + a + “ to “ + b); else { hanoi(n-1, a, c, b); System.out.println(“Move disk “ + n + “ from “ + a + “ to “ + b); hanoi(n-1, c, a, b); } Solution for hanoi(3, 1, 2, 3) (move 3 disks from tower 1 to tower 2) n = 3, recursively call hanoi(2, 1, 3, 2) n = 2, recursively call hanoi(1, 1, 2, 3) n = 1, print Move disk 1 from 1 to 2 print Move disk 2 from 1 to 3 recursively call hanoi(1, 2, 3, 1) n = 1, print Move disk 1 from 2 to 3 print Move disk 3 from 1 to 2 recursively call hanoi(2, 3, 2, 1) n = 2, recursively call hanoi(1, 3, 1, 2) n = 1, print Move disk 1 from 3 to 1 print Move disk 2 from 3 to 2 recursively call hanoi(1, 1, 2, 3) n = 1, print Move disk 1 from 1 to 2 done

Computing GCD Recursively if(m>=n) System.out.println("The gcd of " + m + " and " + n + " is " + computeGCD(m, n)); else System.out.println("The gcd of " + m + " and " + n + " is " + computeGCD(n, m)); public static int computeGCD(int a, int b) { if(a%b==0) return b; else return computeGCD(b, a%b); } Consider m = 45, n = 87 m < n so call computeGCD(n, m) a = 87, b = 45 a%b!=0 computeGCD(45, 87%45 = 42 a = 45, b = 42 a%b != 0 computeGCD(42, 45%42 = 3 a = 42, b = 3 a%b == 0, return b (3)

Other Recursive Problems (without solutions) 8 Queens Given 8 queens and a chess board, position each queen on the board such that no queen can capture another queen generalize to the N queens problem Knight’s Tour Given a knight on a chess board, find the sequence of moves that allow you to move the knight from square to square such that it lands on every square of the chess board exactly 1 time Knapsack Given n items, each with its own weight and value, and a knapsack that can store a given capacity in weight, find the collection of items that do not exceed the capacity that maximum the value (see the next slide)

Knapsack Consider these items: item 1, weight 15, value 13 item 2, weight 12, value 6 item 3, weight 20, value 16 item 4, weight 22, value 15 item 5, weight 14, value 10 item 6, weight 18, value 15 item 7, weight 22, value 19 item 8, weight 14, value 12 item 9, weight 13, value 9 item 10, weight 17, value 15 item 11, weight 16, value 14 item 12, weight 15, value 12 The knapsack can hold a total weight of 88, which items do you place in it to maximum the value? With 12 items, there are 4096 possible combinations of items This is reduced because some combinations exceed the maximum well before we consider all items This is one of a class of problems that have a computational complexity of O(2n) (at least as provable today)