Topic 9 Introduction to Recursion I t d ti t R i "To a man with a hammer, "T ith h everything looks like a nail" everything looks like a nail -Mark Twain Mark Twain CS 307 Fundamentals of 1 Computer Science Introduction to Recursion
Underneath the Hood. CS 307 Fundamentals of 2 Computer Science Introduction to Recursion
The Program Stack 8 When you invoke a method in your code what happens when that method is completed? FooObject f = new FooObject(); int x = 3; f.someFooMethod(x); f.someBarMethod(x); 8 How does that happen? pp 8 What makes it possible? CS 307 Fundamentals of 3 Computer Science Introduction to Recursion
Methods for Illustration 200 200 public void someFooMethod(int z) bli id F M th d(i t ) 201{ int x = 2 * z; 202 202 System.out.println(x); i l ( ) } 300 public void someBarMethod(int y) 301 { 301 { i int x = 3 * y; 3 * 302 someFooMethod(x); 303 System.out.println(x); } CS 307 Fundamentals of 4 Computer Science Introduction to Recursion
The Program Stack 8 When your program is executed on a processor the commands are converted into another set of instructions and assigned memory locations. – normally a great deal of expansion takes place 101 FooObject f = new FooObject(); 102 int x = 3; 103 f.someFooMethod(x); 104 f 104 f.someBarMethod(x); h d( ) 8 Von Neumann Architecture CS 307 Fundamentals of 5 Computer Science Introduction to Recursion
Basic CPU Operations 8 A CPU 8 A CPU works via a fetch k i f t h command / execute command loop and a program counter loop and a program counter 8 Instructions stored in memory (Just like data!) (Just like data!) 101 FooObject f = new FooObject(); j j (); 102 int x = 3; 103 f.someFooMethod(x); 104 f 104 f.someBarMethod(x); B M th d( ) 8 What if someFooMethod is stored at memory location 200? memory location 200? CS 307 Fundamentals of 6 Computer Science Introduction to Recursion
More on the Program Stack 101 FooObject f = new FooObject(); 102 int x = 3; 103 f.someFooMethod(x); 104 f.someBarMethod(x); 8 Line 103 is really saying go to line 200 with f as the implicit parameter and x as the explicit parameter 8 When someFooMethod is done what happens? pp A. Program ends B. goes to line 103 C Goes back to whatever method called it C. Goes back to whatever method called it CS 307 Fundamentals of 7 Computer Science Introduction to Recursion
Activation Records and the Program Stack Program Stack 8 When a method is invoked all the relevant i f information about the current method ti b t th t th d (variables, values of variables, next line of code to be executed) is placed in an d t b t d) i l d i activation record 8 The activation record is pushed onto the program stack 8 A stack is a data structure with a single access point, the top. p , p CS 307 Fundamentals of 8 Computer Science Introduction to Recursion
The Program Stack 8 Data may either be added ( pushed) or removed (popped) from top a stack but it is always f from the top. – A stack of dishes – which dish do we have easy access to? CS 307 Fundamentals of 9 Computer Science Introduction to Recursion
Using Recursion Using Recursion CS 307 Fundamentals of 10 Computer Science Introduction to Recursion
A Problem 8 W it 8 Write a method that determines how much space is take up th d th t d t i h h i t k by the files in a directory 8 A directory can contain files and directories A directory can contain files and directories 8 How many directories does our code have to examine? 8 How would you add up the space taken up by the files in a single directory – Hint: don't worry about any sub directories at first 8 Directory and File classes 8 Directory and File classes 8 in the Directory class: public File[] getFiles() public Directory[] getSubdirectories() 8 in the File class public int getSize() bli i t tSi () CS 307 Fundamentals of 11 Computer Science Introduction to Recursion
Attendance Question 2 8 How many levels of directories have to be visited? A. 0 B. Unknown U o C. Infinite D 1 D. 1 E. 8 CS 307 Fundamentals of 12 Computer Science Introduction to Recursion
Sample Directory Structure scottm AP cs307 m2.txt m1.txt A.pdf AB.pdf hw a1.htm a2.htm a3.htm a4.htm CS 307 Fundamentals of 13 Computer Science Introduction to Recursion
Code for getDirectorySpace() public int getDirectorySpace(Directory d) bli i t tDi t S (Di t d) { int total = 0; File[] fileList = d.getFiles(); e[] e st d.get es(); for(int i = 0; i < fileList.length; i++) total += fileList[i].getSize(); Directory[] dirList = d.getSubdirectories(); for(int i = 0; i < dirList.length; i++) t t l + total += getDirectorySpace(dirList[i]); tDi t S (di Li t[i]) return total; } CS 307 Fundamentals of 14 Computer Science Introduction to Recursion
Attendance Question 3 8 Is it possible to write a non recursive method to do this? A. Yes B. No CS 307 Fundamentals of 15 Computer Science Introduction to Recursion
Iterative getDirectorySpace() public int getDirectorySpace(Directory d) public int getDirectorySpace(Directory d) { ArrayList dirs = new ArrayList(); File[] fileList; Directory[] dirList; y dirs.add(d); Directory temp; int total = 0; while( ! dirs.isEmpty() ) hil ( ! di i () ) { temp = (Directory)dirs.remove(0); fileList = temp.getFiles(); for(int i = 0; i < fileList length; i++) for(int i 0; i < fileList.length; i++) total += fileList[i].getSize(); dirList = temp.getSubdirectories(); for(int i =0; i < dirList.length; i++) dirs.add( dirList[i] ); } return total; } } CS 307 Fundamentals of 16 Computer Science Introduction to Recursion
Simple Recursion Examples Simple Recursion Examples CS 307 Fundamentals of 17 Computer Science Introduction to Recursion
Wisdom for Writing Recursive Methods CS 307 Fundamentals of 18 Computer Science Introduction to Recursion
The 3 plus 1 rules of Recursion 1. Know when to stop 2. Decide how to take one step 3. Break the journey down into that step and a smaller journey s a e jou ey 4. Have faith From Common Lisp: A Gentle Introduction to Introduction to Symbolic Computation by David Touretzky CS 307 Fundamentals of 19 Computer Science Introduction to Recursion
Writing Recursive Methods 8 R l 8 Rules of Recursion f R i 1. Base Case: Always have at least one case that can be solved without using recursion can be solved without using recursion 2. Make Progress: Any recursive call must progress toward a base case. progress toward a base case. 3. "You gotta believe." Always assume that the recursive call works. (Of course you will have to design it and test it to see if it works or prove that it always works.) A recursive solution solves a small part of A recursive solution solves a small part of the problem and leaves the rest of the problem in the same form as the original problem in the same form as the original CS 307 Fundamentals of 20 Computer Science Introduction to Recursion
N! 8 the classic first recursion problem / example 8 N! 5! = 5 * 4 * 3 * 2 * 1 = 120 int res = 1; for(int i = 2; i <= n; i++) res *= i; CS 307 Fundamentals of 21 Computer Science Introduction to Recursion
Factorial Recursively 8 Mathematical Definition of Factorial 0! = 1 N! = N * (N - 1)! The definition is recursive. // pre n >= 0 public int fact(int n) { if(n == 0) { ( ) return 1; else return n * fact(n 1); return n * fact(n-1); } CS 307 Fundamentals of 22 Computer Science Introduction to Recursion
Big O and Recursion 8 Determining the Big O of recursive methods can be tricky. 8 A recurrence relation exits if the function is defined recursively. 8 The T(N), actual running time, for N! is recursive ecu s e 8 T(N) fact = T(N-1) fact + O(1) 8 This turns out to be O(N) 8 This turns out to be O(N) – There are N steps involved CS 307 Fundamentals of 23 Computer Science Introduction to Recursion
Common Recurrence Relations 8 T(N) 8 T(N) = T(N/2) + O(1) -> O(logN) T(N/2) + O(1) > O(l N) – binary search 8 T(N) = T(N-1) + O(1) -> O(N) 8 T(N) = T(N-1) + O(1) -> O(N) – sequential search, factorial 8 T(N) = T(N/2) + T(N/2) + O(1) -> O(N), ( ) ( ) ( ) ( ) ( ), – tree traversal 8 T(N) = T(N-1) + O(N) -> O(N^2) – selection sort 8 T(N) = T(N/2) + T(N/2) + O(N) -> O(NlogN) – merge sort t 8 T(N) = T(N-1) + T(N-1) + O(1) -> O(2^N) – Fibonacci – Fibonacci CS 307 Fundamentals of 24 Computer Science Introduction to Recursion
Tracing Fact With the Program Stack Program Stack System.out.println( fact(4) ); System.out.println( fact(4) ); top System.out.println( fact(4) ); CS 307 Fundamentals of 25 Computer Science Introduction to Recursion
Calling fact with 4 4 4 in method fact in method fact n partial result = n * fact(n-1) top System.out.println( fact(4) ); CS 307 Fundamentals of 26 Computer Science Introduction to Recursion
Calling fact with 3 3 in method fact n n partial result = n * fact(n-1) 4 4 in method fact i th d f t n top partial result = n * fact(n-1) System.out.println( fact(4) ); CS 307 Fundamentals of 27 Computer Science Introduction to Recursion
Recommend
More recommend