1 / 39

Chapter 11- Recursion

Chapter 11- Recursion. Overview. What is recursion? Basics of a recursive function. Understanding recursive functions. Other details of recursion. Binary Search Algorithm Review. What is recursion?. What is recursion?.

major
Download Presentation

Chapter 11- Recursion

An Image/Link below is provided (as is) to download presentation Download Policy: Content on the Website is provided to you AS IS for your information and personal use and may not be sold / licensed / shared on other websites without getting consent from its author. Content is provided to you AS IS for your information and personal use only. Download presentation by click this link. While downloading, if for some reason you are not able to download a presentation, the publisher may have deleted the file from their server. During download, if you can't get a presentation, the file might be deleted by the publisher.

E N D

Presentation Transcript


  1. Chapter 11- Recursion

  2. Overview • What is recursion? • Basics of a recursive function. • Understanding recursive functions. • Other details of recursion. • Binary Search Algorithm • Review.

  3. What is recursion?

  4. What is recursion? • Recursion is when a method calls itself. Thus in the definition of the method there is a call to the method. public void method1(int someInt) { if(someInt == 1) return 1; return method1(someInt-1) + 8; }

  5. How is recursion useful? • Just another way of solving problems. • Sometimes the recursive way of solving problems is more intuitive and easier to understand than any other method. • Basically a divide and conquer method. • Understanding it will help you pass CS courses.

  6. Basics of a recursive function.

  7. Recursion • Recursive solutions take a difficult problem that you don’t understand and divide it into 2 parts: • A simple piece that you understand. • Another complicated piece that is simpler than the original problem.

  8. Recursive parts • These 2 pieces directly relate to the 2 required parts of any recursive method: • A base case: has no recursive calls. • A recursive piece: Has a recursive call to a simpler or smaller version of the current problem. • These two parts are usually represented in an if-else statement in your method.

  9. Recursive pieces public void someMethod(int someParam) { if(someParam == 5) return 12; else { int result; result = someMethod(someParam – 5) + 1; return result; } } Base case Recursive step

  10. Understanding Recursive functions

  11. Recursive functions • The first thing to do with recursive functions is learn how to read them and how they compute things. • Each time there is a recursive call to the function, another copy of the function is made in the computer. Only when these copies return their values do they disappear.

  12. Recursive example public void recursive1(int someNum) { if(someNum <= 1) System.out.println(“Base Case:1”); else { recursive1(someNum -1); System.out.println(“Recursive step: “ + someNum); } } What would a call recursive1(4) print out to the screen?

  13. Recursive example recursive1(4) 4 Not <= 1 Call recursive1(4-1) Print out mesg. Recursive step:4 recursive1(3) 3 Not <= 1 Call recursive1(3-1) Print out mesg. Recursive step:3 recursive1(2) 2 Not <= 1 Call recursive1(2-1) Print out mesg. Recursive step:2 recursive1(1) 1 <= 1 print out “Base Case” Base Case:1

  14. What prints out Base Case: 1 Recursive Step: 2 Recursive Step: 3 Recursive Step: 4

  15. Recursive example public void recursive2(int someNum) { if(someNum <= 1) System.out.println(“Base Case:1”); else { System.out.println(“Recursive step: “ + someNum); recursive2(someNum -1); } } What would a call recursive2(3) print out to the screen?

  16. Recursive example public int recursive3(int someNum) { if(someNum <= 1) return 1; return recursive3(someNum-1) + 1; } What would a call System.out.println(recursive3(2)); print out to the screen? What would a call System.out.println(recursive3(4)); print out to the screen?

  17. Recursive example public int recursive4(int someNum) { if(someNum <= 1) { System.out.println(someNum); return someNum; } int I = recursive4(someNum-1) + 3; System.out.println(I); return I; } What would a call recursive4(2) print out to the screen? What would System.out.println(recursive4(2)) print out to the screen? What would a call recursive4(4) print out to the screen?

  18. Recursive example public int recursive5(int someNum) { if(someNum <= 1) return 1; return recursive5(someNum-1) + someNum; } What would a call recursive5(2) print out to the screen? What would a call recursive5(3) print out to the screen? What would a call recursive5(5) print out to the screen? What is this function doing?

  19. Writing recursive functions • Now that you understand how recursive methods work, you can start practicing them. • Always remember two things: • Must have a base case • The recursive call should usually make things simpler or smaller.

  20. Recursive writing practice. • Without looking at the previous examples, try to write a recursive method to calculate the sum of the first N integers(1+2+3+…+(N-1) + N = N + sum(first N-1 integers)). • Write a recursive method for the factorial function. N! = N*(N-1)*…*3*2*1 • Note that this means N! = N*(N-1)!

  21. Other Recursive details

  22. We’ve already mentioned this, but... • Always have a base case! • Your recursive call should be smaller or simpler than your current state. • If you violate either of these you might have an infinite loop.

  23. Bad recursion examples- Don’t do these! public int badRecursion(int someNum) { return badRecursion(someNum-1); } public int alsoBadRecursion(int someNum) { if(someNum == 1) return 1; return alsoBadRecursion(someNum)-1; }

  24. You can use recursion to help with checking output- no while loops. public void Division() { System.out.println(“Enter numerator: “); int num = SavitchIn.readLineInt(); System.out.println(“Enter denominator: “); int den = SavitchIn.readLineInt(); if(den == 0) { System.out.println(“Bad denominator.”); Division(); } else System.out.println(num/den); }

  25. Recursion vs. Iteration • EVERY recursive method can be rewritten with loops(for or while or do-while). Writing a method with loops is called iteration. • Iteration is faster than recursion(in general).

  26. So why use recursion? • Sometimes a recursive solution is easier to understand than an iterative solution. • Sometimes speed is not necessary and ease of understanding the code is necessary(or desired).

  27. Binary Search Algorithm

  28. Recursive case study- Binary Search • A common example for the somewhat practical use of recursion is the Binary Search. • The Binary Search is pretty close to how we search as humans. • Unlike the Sequential Search that we saw before, the array must be ordered for the Binary Search to work.

  29. Binary Search Algorithm • Given a range of the array to search, we look at the midpoint and compare it against what we are searching for. • If it is equal, we are done. • If what we are searching for is greater than the middle element, continue searching the lesser half of the array. • Else search the greater half of the array.

  30. Binary Search Examples - General • Imagine searching a phonebook for the name “Eric Davis”. • We first flip open the phone book at the half way point and see a name “Yvonne Martinez.” This is past Davis so we search the names again only in the half before Martinez. • The next search opens the book to “Earl Crass.” This is closer to Davis, but still isn’t quite there. Now we are too early before Davis, so we look between Crass and Martinez for our next search. • Continue this on until we either find Davis or have a range that has 0 elements in it.

  31. Binary Search examples -arrays. Searching for 6 -1 0 1 3 4 6 7 8 10 10 12 13 20 21 22 Too big! Look left 6 -1 0 1 3 4 6 7 X X X X X X X X Too small! Look right 6 X X X X 4 6 7 X X X X X X X X Found it!(Just right) 6

  32. Binary Search examples -arrays. Searching for 5 -1 0 1 3 4 6 7 8 10 10 12 13 20 21 22 Too big! Look left 5 -1 0 1 3 4 6 7 X X X X X X X X Too small! Look right 5 X X X X 4 6 7 X X X X X X X X Too big! Look left 5 X X X X 4 X X X X X X X X X X Too small! Look right 5 X X X X X X X X X X X X X X X No more elements. Not found! 5

  33. Binary Search Algorithm- Pseudocode //Given a range begin to end to search for key //using array arr if( there are no elements) return not found; mid = midpoint between begin and end. If(key equals the mid element of the array) return found; if(key greater than mid element) return BinarySearch(mid+1 to end); else return BinarySearch(begin to mid-1) Base Case Base Case Recursive Step

  34. Binary Search Algorithm-Code //using an array called a. See p.744 for more code. public int Search(int key, int first,int last) { int result =-1; int mid; if(first > last) return -1; //not found mid=(first+last)/2; if(key == a[mid]) return mid; //found if(key < a[mid]) return Search(key, first, mid-1); return Search(key, mid+1, last); }

  35. Review

  36. Recursive Review • How can you tell if a function is recursive? • What two pieces must you have in every correct recursive function? • Name two ways of creating infinite loops without using looping structures(using only recursive functions).

  37. Recursive Review public int recursive3(int someNum) { if(someNum <= 1) return 1; return recursive3(someNum-1) + 2; } What would a call System.out.println(recursive3(2)); print out to the screen? What would a call System.out.println(recursive3(4)); print out to the screen?

  38. Recursive Review • Write a recursive method in Java to implement the following math function: f(1) = 1 f(n) = f(n-1)+ 3*n

  39. Recursive Review • Can you change every recursive method into an iterative one? Which method would likely be faster? • Why would you want to use a recursive method instead of an iterative one? • Describe the Binary Search algorithm in your own words. Will it work on unordered arrays?

More Related