Chapter 11- Recursion
Jan 16, 2016
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?
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;}
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.
Basics of a recursive function.
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.
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.
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
Understanding Recursive functions
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.
Recursive examplepublic 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?
Recursive examplerecursive1(4)4 Not <= 1Call recursive1(4-1)Print out mesg.
recursive1(3)3 Not <= 1Call recursive1(3-1)Print out mesg.
recursive1(2)2 Not <= 1Call recursive1(2-1)Print out mesg.
recursive1(1)1 <= 1print out “Base Case” Base Case:1
Recursive step:2
Recursive step:3
Recursive step:4
What prints out
Base Case: 1Recursive Step: 2Recursive Step: 3Recursive Step: 4
Recursive examplepublic 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?
Recursive examplepublic 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?
Recursive examplepublic 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)) printout to the screen?What would a call recursive4(4) print out to the screen?
Recursive examplepublic 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?
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.
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)!
Other Recursive details
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.
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;}
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);}
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).
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).
Binary Search Algorithm
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.
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.
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.
Binary Search examples -arrays. Searching for 6-1 0 1 3 4 6 7 8 10 10 12 13 20 21 22
6
-1 0 1 3 4 6 7 X X X X X X X X
6
X X X X 4 6 7 X X X X X X X X
6 Found it!(Just right)
Too big! Look left
Too small! Look right
Binary Search examples -arrays. Searching for 5-1 0 1 3 4 6 7 8 10 10 12 13 20 21 22
5
-1 0 1 3 4 6 7 X X X X X X X X
5
X X X X 4 6 7 X X X X X X X X
5 Too big! Look left
Too big! Look left
Too small! Look right
X X X X 4 X X X X X X X X X X
5 Too small! Look right
X X X X X X X X X X X X X X X
5 No more elements. Not found!
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
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 foundmid=(first+last)/2;if(key == a[mid])
return mid; //foundif(key < a[mid])
return Search(key, first, mid-1);return Search(key, mid+1, last);
}
Review
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).
Recursive Reviewpublic 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?
Recursive Review
Write a recursive method in Java to implement the following math function:
f(1) = 1
f(n) = f(n-1)+ 3*n
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?