This preview shows pages 1–8. Sign up to view the full content.
This preview has intentionally blurred sections. Sign up to view the full version.
View Full DocumentThis preview has intentionally blurred sections. Sign up to view the full version.
View Full DocumentThis preview has intentionally blurred sections. Sign up to view the full version.
View Full DocumentThis preview has intentionally blurred sections. Sign up to view the full version.
View Full Document
Unformatted text preview: Click to edit Master subtitle style © 2009 Dr. Tim Recursion Dr. Tim Margush University of Akron © 2009 © 2009 Dr. Tim Goals • Be able to describe a recursive solution to a problem • Know the basic techniques for writing a recursive method • Identify tail recursion and convert it to iteration (c) 2009 Tim margush © 2009 Dr. Tim Recursion • A seemingly circular definition or solution – The solution requires the use of the solution, usually applied to solve a simpler sub problem that will in turn help solve the original problem • A method that calls itself as one or more of its internal steps (c) 2009 Tim margush © 2009 Dr. Tim a+b • Many simple operations can be cast into a recursive definition – If we know how to increment and decrement, but are not good with general addition, then • a+b = (a++) + (b) if b>0 = a if b==0 = (a) + (b++) if b<0 – If powers give us problems, then • an = a(an1) if n>0 = 1 if n==0 © 2009 Dr. Tim © 2009 Dr. Tim Translating to Java © 2009 Dr. Tim public int add(int a, int b){ if (b>0) return add(a++, b); else if (b==0) return a; else return add(a, b++); } private int power(int a, int n){ if (n>0) return a*power(a,n1); else return 1; } © 2009 Dr. Tim contains • In a linked list, contains might be written recursively (c) 2009 Tim margush public boolean contains(E target){ return contains(head, target); } private static boolean contains(Node h, E target){ if (h==null) return false; else if (h.data.equals(target)) return true; else return contains(h.next, target); } © 2009 Dr. Tim Recursive Definitions • Require a base case – An answer that does not make a circular reference • b = 0; a + b = a • n = 0;...
View
Full
Document
This note was uploaded on 02/22/2011 for the course CS 463 taught by Professor Dr. tim margush during the Fall '09 term at The University of Akron.
 Fall '09
 Dr. Tim Margush
 Algorithms, Data Structures, Recursion

Click to edit the document details