Week 11Recursion
© 2004 Pearson Addison-Wesley. All rights reserved 5-2Copyright WarningCOMMONWEALTH OF AUSTRALIACopyright Regulations 1969...
© 2004 Pearson Addison-Wesley. All rights reserved 5-3What is Recursion?• Recursion is a technique, which is used to solve...
© 2004 Pearson Addison-Wesley. All rights reserved 5-4What Problems Can Use Recursion?• In order to solve a problem with r...
© 2004 Pearson Addison-Wesley. All rights reserved 5-5Pass the Parcel• Problem: unwrap the layers of paper around aparcel ...
© 2004 Pearson Addison-Wesley. All rights reserved 5-6Implementing Recursion in Java• Remember, we have to think of a recu...
© 2004 Pearson Addison-Wesley. All rights reserved 5-7Methods Can Call Methods• We know that methods can call other method...
© 2004 Pearson Addison-Wesley. All rights reserved 5-8The Blah Methodint blah(int value){int result;result = value * blah(...
© 2004 Pearson Addison-Wesley. All rights reserved 5-9A Blah Method That Stopsint blah(int value){int result;if (value == ...
© 2004 Pearson Addison-Wesley. All rights reserved 5-10The Factorial Function• In maths, Fact(X) = X * all the numbers bel...
© 2004 Pearson Addison-Wesley. All rights reserved 5-11The Factorial Functionint factorial(int value){int result;if (value...
© 2004 Pearson Addison-Wesley. All rights reserved 5-12But, How Can a Method Call Itself?• I mean, wont the second method ...
© 2004 Pearson Addison-Wesley. All rights reserved 5-13Why Do We Need Recursion?• Well, most of the time we dont. However,...
© 2004 Pearson Addison-Wesley. All rights reserved 5-14Find Files Algorithm: IncompletefindFiles(Folder F, String suffix){...
© 2004 Pearson Addison-Wesley. All rights reserved 5-15Find Files Algorithm: CompletefindFiles(Folder F, String suffix){Li...
© 2004 Pearson Addison-Wesley. All rights reserved 5-16Find Files as Java Code• Read through the Java code from the lab• T...
© 2004 Pearson Addison-Wesley. All rights reserved 5-17The Towers of Hanoi Game• Move the tower of disks from the left col...
© 2004 Pearson Addison-Wesley. All rights reserved 5-18Towers of Hanoi: RecursivelymoveTower(int N, int startPosn,int endP...
© 2004 Pearson Addison-Wesley. All rights reserved 5-19Towers of Hanoi as Java Code• Read through the code from the lab.
© 2004 Pearson Addison-Wesley. All rights reserved 5-20Recursion as a Problem Solver• Recursion can be a very elegant way ...
© 2004 Pearson Addison-Wesley. All rights reserved 5-21The Fibonnaci Series1, 1, 2, 3, 5, 8, 13, 21, 34, ...• Each number ...
© 2004 Pearson Addison-Wesley. All rights reserved 5-22Reversing a String• Group Activity: Write a recursive method toreve...
Upcoming SlideShare
Loading in …5
×

Week11

165 views
92 views

Published on

Published in: Technology, Education
0 Comments
0 Likes
Statistics
Notes
  • Be the first to comment

  • Be the first to like this

No Downloads
Views
Total views
165
On SlideShare
0
From Embeds
0
Number of Embeds
6
Actions
Shares
0
Downloads
2
Comments
0
Likes
0
Embeds 0
No embeds

No notes for slide

Week11

  1. 1. Week 11Recursion
  2. 2. © 2004 Pearson Addison-Wesley. All rights reserved 5-2Copyright WarningCOMMONWEALTH OF AUSTRALIACopyright Regulations 1969WARNINGThis material has been copied and communicated to you by oron behalf of Bond University pursuant to Part VB of theCopyright Act 1968 (the Act).The material in this communication may be subject to copyrightunder the Act. Any further copying or communication of thismaterial by you may be the subject of copyright protectionunder the Act.Do not remove this notice.
  3. 3. © 2004 Pearson Addison-Wesley. All rights reserved 5-3What is Recursion?• Recursion is a technique, which is used to solve aspecific class of problems• With these type of problems: You can solve one part of the problem, and This leaves a smaller problem which is exactly the sametype as the original problem• 99% of problems do not need recursion.• However, 1% of problems do need recursion!• The hardest part of recursion is how to visualise aproblem and see how we can apply the recursiontechnique• Hint: if you are asked to do something recursively,it can be done that way. Try to visualise how
  4. 4. © 2004 Pearson Addison-Wesley. All rights reserved 5-4What Problems Can Use Recursion?• In order to solve a problem with recursion, youneed 3 things to be true:1 Given a problem, you can solve part of the problemimmediately2 This leaves a smaller problem of exactly the same type3 There is a “base case”, i.e. a simplest problem, which canbe solved without step 2.• Step 2 is the “recursion” part of the problemsolving• Lets have a look at a game which uses recursion
  5. 5. © 2004 Pearson Addison-Wesley. All rights reserved 5-5Pass the Parcel• Problem: unwrap the layers of paper around aparcel in order to reveal the present inside• We can solve this iteratively: While (there is paper) remove paper.• Lets also solve this recursively:1 Unwrap one piece of paper2 If (we find the prize) stop3 Otherwise, pass the parcel to someone else• We solve part of the problems with step 1. Thisleaves a smaller problem which is solved with step3. The base case is step 2.• Note: the 3 steps for recursion dont have to occurin order
  6. 6. © 2004 Pearson Addison-Wesley. All rights reserved 5-6Implementing Recursion in Java• Remember, we have to think of a recursivesolution to the problem first!• We use a method to solve part of the problem, i.e.step 1.• To solve the smaller problem, we call a newinstance of the same method with the left-overproblem: this is step 2, i.e. the recursion.• We need to ensure that, at some point, we wontcall a new instance of the same method: this isstep 3, i.e. the base case.• At this point, a typical question: how can a Javamethod call itself? What does this mean?
  7. 7. © 2004 Pearson Addison-Wesley. All rights reserved 5-7Methods Can Call Methods• We know that methods can call other methods:public static void main(){int age;System.out.print("Whats your age: ");age= scan.nextInt();}• What would happen if a method called itself?• Lets see...
  8. 8. © 2004 Pearson Addison-Wesley. All rights reserved 5-8The Blah Methodint blah(int value){int result;result = value * blah(value -1);return(result);}• If in main() we do x= blah(4); what happens? blah() tries to calculate 4 * blah(3) but then another blah() tries to calculate 3*blah(2)• This thing is never going to stop! So its prettyuseless.• What if we make it stop when the value is 1? blah(X) is X * blah(X-1) but blah(1) is always exactly 1
  9. 9. © 2004 Pearson Addison-Wesley. All rights reserved 5-9A Blah Method That Stopsint blah(int value){int result;if (value == 1)result = 1;elseresult = value * blah(value-1);return(result);}• This is known as a recursive method or a recursivefunction: the operation depends on itself.• For it to work properly, the function at some pointmust not call itself. It must bottom out.
  10. 10. © 2004 Pearson Addison-Wesley. All rights reserved 5-10The Factorial Function• In maths, Fact(X) = X * all the numbers below it• For example, Fact(7) = 7 * 6 * 5 * 4 * 3 * 2 * 1• But note: Fact(7) = 7 * (6 * 5 * 4 * 3 * 2 * 1), soFact(7) = 7 * Fact(6)• So, we can also define Fact(X) recursively: Fact(X) = X * Fact(X-1), when X>1 Fact(1) = 1• Hmm, thats exactly the blah() method we havealready written. Lets rename it factorial().
  11. 11. © 2004 Pearson Addison-Wesley. All rights reserved 5-11The Factorial Functionint factorial(int value){int result;if (value==1)result=1;elseresult= value * blah(value-1);return(result);}Base caseThe RecursionSolve one part of the problem
  12. 12. © 2004 Pearson Addison-Wesley. All rights reserved 5-12But, How Can a Method Call Itself?• I mean, wont the second method trample over allof the local variables and parameters in the firstmethod? How can there be two methods at thesame time?• Because, when a method starts up, it gets its owncopies of the parameters and any local variables.• So when factorial() with parameter 5 callsfactorial() with parameter 4, they each haveseparate parameter variables.
  13. 13. © 2004 Pearson Addison-Wesley. All rights reserved 5-13Why Do We Need Recursion?• Well, most of the time we dont. However,sometimes it is very hard to avoid it.• Recursion is used when a problem is best solvedby doing some of the work, which leaves a smallerproblem that can be solved the same way.• Here is a common real-world problem that needsrecursion:
  14. 14. © 2004 Pearson Addison-Wesley. All rights reserved 5-14Find Files Algorithm: IncompletefindFiles(Folder F, String suffix){List L;get list L of everything in F;for each thing in list L{if (it is a file and ends in suffix)print it out;if (we have found another folder G)what do we do here?}}• What do we do on the red line? We could cut &paste the algorithm inside more { ... }.• But what if there are folders inside G? And what ifthey have folders?
  15. 15. © 2004 Pearson Addison-Wesley. All rights reserved 5-15Find Files Algorithm: CompletefindFiles(Folder F, String suffix){List L;get list L of everything in F;for each thing in list L{if (it is a file and ends in suffix)print it out;if (we have found another folder G)findFiles(G, suffix);}}• When we find a sub-folder, we start a separate methodto deal with the files in that folder.• And if the sub-folder has its own sub-folder, we do thesame.• Eventually, we hit folders that only have files, and sothe recursion will bottom-out.
  16. 16. © 2004 Pearson Addison-Wesley. All rights reserved 5-16Find Files as Java Code• Read through the Java code from the lab• Try it out with “H:SD1” as the folder, and “java”as the suffix• Use the debugger to stop after the name of eachthing in the list has been found• As the recursion happens, the debugger will showyou each instance of the method on the left
  17. 17. © 2004 Pearson Addison-Wesley. All rights reserved 5-17The Towers of Hanoi Game• Move the tower of disks from the left column to theright column.• Move only 1 disk at a time. Cannot put a biggerdisk on a smaller disk.• Hint: If we would move the tower consisting of thelight-blue disk upwards to the middle column, wecould move the green disk to the right column.
  18. 18. © 2004 Pearson Addison-Wesley. All rights reserved 5-18Towers of Hanoi: RecursivelymoveTower(int N, int startPosn,int endPosn, int tempPosn){// Move the N-1 tower from its start position// to the temp positionmoveTower(N-1, startPosn, tempPosn, endPosn);// Move the Nth disk from start to endmoveOneDisk(startPosn, endPosn);// And move the N-1 tower on top of Nth diskmoveTower(N-1, tempPosn, endPosn, startPosn);}• But, we have forgotten about the “bottom out”condition!• How can we rectify this?
  19. 19. © 2004 Pearson Addison-Wesley. All rights reserved 5-19Towers of Hanoi as Java Code• Read through the code from the lab.
  20. 20. © 2004 Pearson Addison-Wesley. All rights reserved 5-20Recursion as a Problem Solver• Recursion can be a very elegant way of solving aproblem.• You need: a part of the problem which can be solvedimmediately a way of expressing the solution of the rest ofthe problem in terms of itself• The idea is to do some work, but “pass the buck”(i.e. most of the problem) on to someone else.• Eventually, all of the problem can get solved.
  21. 21. © 2004 Pearson Addison-Wesley. All rights reserved 5-21The Fibonnaci Series1, 1, 2, 3, 5, 8, 13, 21, 34, ...• Each number is equal to the sum of the previoustwo numbers, i.e. Fib(X)= Fib(X-1) + Fib(X-2) but we also need Fib(1)=1, Fib(2)=1 to bottomout.• So, Fib(5)= Fib(4)+Fib(3)• Fib(5)= (Fib(3)+Fib(2)) + (Fib(2)+Fib(1))• Fib(5)=((Fib(2)+Fib(1))+1) + (1 + 1)• Fib(5)= ((1+1)+1) + (1+1) = 5• Group Activity: Write a recursive Fibonacci()method.
  22. 22. © 2004 Pearson Addison-Wesley. All rights reserved 5-22Reversing a String• Group Activity: Write a recursive method toreverse a String.• Hint: get the first letter of the String, and the restof the String.• Hint: then reverse the rest of the string.• Hint: then glue the reversed substring and theletter together again.

×