CS100-Recursion.pptx

advertisement
Recursion
Snarf the code for today’s class.
Where We Are: Tools and Techniques
•
•
•
•
Data Structures, like Lists and Maps
Techniques, like Big O analysis
Classes and Inheritance
The essential process of taking a problem and
solving it with code
All of it happens to be within Java in
this course…but these ideas transcend
Java
Recursion
• When a function calls a
“clone” of itself
• Also, when a Data structure contains a “clone”
of itself (but we will save this one for later)
What to do
• Snarf the code for today’s class if you haven’t
already
• Go to the quiz section of Sakai
• There’s classwork for today there
• Go through and try to answer the questions (feel
free to take you time, think, and ask a friend)
• If you get stuck, run the code and see what’s
going on
• If you finish it all, start on the BONUS section
Two Parts To Every Recursive Function
• Base Case
if(n == 1) return 1;
• Recursive Case
return n*recursiveFunction(n-1);
The basic idea is to get help solving a problem from
coworkers (clones) who work and act like you do.
1. Ask clone to solve a similar, but smaller/simpler problem
2. Use the result
3. Don’t forget step 2!
How you divide the problem is key
Say you want to count the number of “a”s in a
string.
How could you solve that problem recursively?
Hint: how many “a”s does a string of length 0
have?
How you divide the problem is key
isPalindrome(String s)
abaXaba -> true
abba -> true
abab -> false
Download