Download Recursion in Computer Science: Power and String Reversal and more Study notes Computer Science in PDF only on Docsity!
Introduction to Computer Science
II CS112-2008S-14More Recursion David GallesDepartment of Computer ScienceUniversity of San Francisco
14-0:^ Recursion^ What is a really easy (small!) version of theproblem, that I could solve immediately? (Basecase)^ How can I make the problem smaller?^ Assuming that I could magically solve the smallerproblem, how could I use that solution to solve theoriginal problem (Recursive Case)
14-2:^ Recursion – Power int power(int x, int n)^ What is the base case?^ What is a version of the problem that is easy,that we can solve immediately?
14-3:^ Recursion – Power int power(int x, int n)^ What is the base case?^ Raising a number to the 1st power is easy^1 x==
x
int power(int x, int n){ if (n == 1){ return x;} }
14-5:^ Recursion – Power int power(int x, int n)^ What is the recursive case?^ How do we make the problem smaller?n−^ x
1 is a smaller problem than
n x
How do we use the solution to the smallerproblem to solve the original problem?n^ n−^ x==^ x
1 ∗^ x
14-6:^ Recursion – Power int power(int x, int n){ if (n == 1){ return x;} else{ return x * power(x, n - 1);} }^ What about
0 x?
14-8:^ Infinite Recursion^ What happens if we forget the base case? int power(int x, int n){ return x * power(x, n - 1);}
14-9:^ Infinite Recursion^ What happens if we don’t make progress towardsthe base case? int power(int x, int n){ if (n == 0){ return 1;} else{ return power(x, n);} }
14-11:^ Recursion – Reverse^ public static String reverse(String s){ if (s.length() <= 1)return s;return reverse(s.substring(1)) + s.charAt(0);}
14-12:^ Tail Recursion^ A method is
tail recursive
if no more work needs to be done after the recursive call We return the value of the recursve call unchanged None of the functions that we have seen so farhave been tail-recursive
14-14:^ Tail Recursion int factorialTR(int n, int result){ if (n == 0)return result;return factorialTR(n - 1, result * n);} int factorial(int n){ return factorialTR(n, 1);}
14-15:^ Tail Recursion^ Tail recursion is a little easier to see with reversinga string:^ Start with an empty result^ Remove first character from input, push it on toresult^ repeat until the input is empty
14-17:^ Tail Recursion^ Why is tail recursion useful?^ “Standard” recursive functions require anactivation record on the stack for each recursivecall^ We need to do some work after the recursivecall is done^ We need the information stored on the stack^ Examples: factorial / reversing
14-18:^ Tail Recursion^ Why is tail recursion useful?^ Tail recursive functions don’t need to maintainthe activation record after the function is called^ Just return the value returned by therecursive call^ We could reuse the same activation record^ Could even change the recursive call to aloop (scheme)