720 likes | 984 Views
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 algorithms and methods for searching arrays To learn about recursive data structures and recursive methods for a LinkedList class
E N D
Recursion Chapter 7 CS 225
Chapter Objectives • To understand how to think recursively • To learn how to trace a recursive method • To learn how to write recursive algorithms and methods for searching arrays • To learn about recursive data structures and recursive methods for a LinkedList class • To understand how to use recursion to • solve the Towers of Hanoi problem • to process two-dimensional images • to solve search problems such as finding a path through a maze using backtracking CS 225
Recursive Thinking • Recursion is a problem-solving approach that can be used to generate simple solutions to certain kinds of problems that would be difficult to solve in other ways • Recursion provides a different way of thinking about a problem • Recursion splits a problem into one or more simpler versions of itself CS 225
Recursive Thinking If there is one figure in the nest process the figure else process the outer figure process the nest inside the outer figure CS 225
When to Use a Recursive Algorithm • There must be at least one case (the base case), for a small value of n, that can be solved directly • A problem of a given size n can be split into one or more smaller versions of the same problem (recursive case) CS 225
Designing a Recursive Algorithm • Recognize the base case and provide a solution to it • Devise a strategy to split the problem into smaller versions of itself while making progress toward the base case • Combine the solutions of the smaller problems in such a way as to solve the larger problem CS 225
String Length Algorithm if the string is empty the length is 0 else length = 1 plus length of substring that excludes the first character CS 225
Proof by induction • Prove the theorem is true for the base case • Show that if the theorem is assumed true for n, then it must be true for n+1 • See the slides on induction CS 225
Proving that a Recursive Method is Correct • Recursive proof is similar to induction • Verify the base case is recognized and solved correctly • Verify that each recursive case makes progress towards the base case • Verify that if all smaller problems are solved correctly, then the original problem is also solved correctly CS 225
Tracing a Recursive Method CS 225
Recursive Definitions of Mathematical Formulas • Mathematicians often use recursive definitions of formulas that lead very naturally to recursive algorithms • Examples include: • Factorial • Powers • Greatest common divisor • If a recursive function never reaches its base case, a stack overflow error occurs CS 225
Recursive Factorial Method • Recursive definition n! = 1 if n=0 n * (n - 1)! if n>0 • Method public static int factorial( int n) { if (n==0) return 1; else return n * factorial( n-1); } CS 225
Recursive Algorithm for xn • Algorithm if n is 0 result is 1 else result is x * xn-1 • Method public static double power( double x, int n) { if (n==0) return 1; else return x * power( x, n-1); CS 225
Greatest Common Divisor • Euclid's algorithm (assumes m>=n) gcd(m, n) = n if n is a divisor of m gcd(m, n) = gcd( n, m % n) otherwise • Method public static double gcd( int m, int n) { if (m%n==0) return n; else if (m<n); return gcd( n, m); else return gcd( n, m%n); } CS 225
Recursion Versus Iteration • There are similarities between recursion and iteration • In iteration, a loop repetition condition determines whether to repeat the loop body or exit from the loop • In recursion, the condition usually tests for a base case • You can always write an iterative solution to a problem that is solvable by recursion • Recursive code may be simpler than an iterative algorithm and thus easier to write, read, and debug • Iteration is usually more efficient CS 225
Iterative Factorial Method public static factorialIter( int n) { int result = 1; for k=1; k<=n; k++) result *= n; return result; } CS 225
Efficiency of Recursion • Recursive methods often have slower execution times when compared to their iterative counterparts • The overhead for loop repetition is smaller than the overhead for a method call and return • If it is easier to conceptualize an algorithm using recursion, then you should code it as a recursive method • The reduction in efficiency does not outweigh the advantage of readable code that is easy to debug CS 225
Recursive Fibonacci Method • Recursive definition fibn = 1 for n = 1,2 fibn-1 + fibn-2 for n>2 • Method public static int fibonacci( int n) { if (n<=2) return 1; else return fibonacci(n-1) + fibonacci(n-2); } CS 225
Efficiency of Recursion: Exponential Fibonacci Inefficient CS 225
An O(n) Recursive Fibonacci Method • To avoid excessive computation, remember the previous two values. • Start the computation public static int fibonacciStart( int n) { return fibo( 1, 0, n); } • Recursive method private static int fibo( int current, int previous, int n) if (n==1) return current; else return fibo( current + previous, current, n-1); } CS 225
Efficiency of Recursion: O(n) Fibonacci Efficient CS 225
Recursive Array Search • Searching an array can be accomplished using recursion • Simplest way to search is a linear search • Examine one element at a time starting with the first element and ending with the last • Base case for recursive search is an empty array • Result is negative one • Another base case would be when the array element being examined matches the target • Recursive step is to search the rest of the array, excluding the element just examined CS 225
Design of Binary Search Algorithm • Binary search can be performed only on an array that has been sorted • Stop cases • The array is empty • Element being examined matches the target • Checks the middle element for a match with the target • Throw away the half of the array that the target cannot lie within CS 225
Binary Search Algorithm CS 225
Trace of a Binary Search CS 225
Efficiency of Binary Search and the Comparable Interface • At each recursive call we eliminate half the array elements from consideration • O(log2n) • Classes that implement the Comparable interface must define a compareTo method that enables its objects to be compared in a standard way • CompareTo allows one to define the ordering of elements for their own classes CS 225
Method Arrays.binarySearch • Java API class Arrays contains a binarySearch method • Can be called with sorted arrays of primitive types or with sorted arrays of objects • If the objects in the array are not mutually comparable or if the array is not sorted, the results are undefined • If there are multiple copies of the target value in the array, there is no guarantee which one will be found • Throws ClassCastException if the target is not comparable to the array elements CS 225
Recursive Data Structures • Computer scientists often encounter data structures that are defined recursively • Trees (Chapter 8) are defined recursively • Linked list can be described as a recursive data structure • Recursive methods provide a very natural mechanism for processing recursive data structures • The first language developed for artificial intelligence research was a recursive language called LISP CS 225
Recursive Definition of a Linked List • A non-empty linked list is a collection of nodes such that each node references another linked list consisting of the nodes that follow it in the list • The last node references an empty list • A linked list is empty, or it contains a node, called the list head, that stores data and a reference to a linked list CS 225
Recursive Size Method CS 225
Recursive toString Method CS 225
Recursive Replace Method CS 225
Recursive Add Method CS 225
Recursive Remove Method CS 225
Problem Solving with Recursion • Will look at two problems • Towers of Hanoi • Counting cells in a blob CS 225
Towers of Hanoi CS 225
Towers of Hanoi (continued) CS 225
Counting Cells in a Blob • Consider how we might process an image that is presented as a two-dimensional array of color values • Information in the image may come from • X-Ray • MRI • Satellite imagery • Etc. • Goal is to determine the size of any area in the image that is considered abnormal because of its color values CS 225
Algorithm for Counting Cells in a Blob if the cell is outside the grid result is 0 if color is not abnormal result is 0 else set color to marker color result = 1 + number of cells in blob that includes a neighbor CS 225