Presentation is loading. Please wait.

Presentation is loading. Please wait.

1 Wright State University, College of Engineering Dr. T. Doom, Computer Science & Engineering CS 241 Computer Programming II CS 241 – Computer Programming.

Similar presentations


Presentation on theme: "1 Wright State University, College of Engineering Dr. T. Doom, Computer Science & Engineering CS 241 Computer Programming II CS 241 – Computer Programming."— Presentation transcript:

1 1 Wright State University, College of Engineering Dr. T. Doom, Computer Science & Engineering CS 241 Computer Programming II CS 241 – Computer Programming II Acknowledgements: These slides were created by Dr. Travis Doom with information, graphics, materials, or kindly aid provided by Gaddis’s “Starting Out with Java”, McConnell’s “Code Complete”, Sierra’s “Head First Java”, Guzdal’s “Introduction to computing and programming with Java”, and Barnes’s “Objects First with Java”.

2 Recursion Recursion - Recursion

3 3 Wright State University, College of Engineering Dr. T. Doom, Computer Science & Engineering CS 241 Computer Programming II Recursion l Recursion specifies (or constructs) a class of objects or methods (or an object from a certain class) by defining –a few very simple base cases or methods (often just one) –rules to break down complex cases into simpler cases l Here is another, perhaps simpler way to understand recursive processes: –Are we done yet? If so, return the results. Without such a termination condition a recursion would go on forever (in an abstract sense. In reality, we run out of memory and get a stack overflow exception). –If not, simplify the problem (move towards a base case), solve the simpler problem(s), and assemble the results into a solution for the original problem. Then return that solution. l "In order to understand recursion, one must first understand recursion." l Recursion: If you still don’t get it, see Recursion

4 4 Wright State University, College of Engineering Dr. T. Doom, Computer Science & Engineering CS 241 Computer Programming II Classic Recursion: n! l Warning: This is a simple illustration of the concept of recursion. It is easy to visualize, but it not intended to be an example of a good use of recursion. public int factorial (int n) { if (n <= 1) { // base case return 1; } else { // recursive step return (n * factorial (n-1)); } } // end factorial public int factorial (int n) { int product = 1; for (int i = 2; i <= n; i++) { product = product * i; } return product; } // end factorial Iterative approach Recursive approach

5 5 Wright State University, College of Engineering Dr. T. Doom, Computer Science & Engineering CS 241 Computer Programming II Memory usage for iterative n! l Iterative implementation requires: – storage of 3 local/stack variables –n multiplications l Considering calling factorial(5) –One stack frame l Overall analysis –Memory: O(3) –Time: O(n) public int factorial (int n) { int product = 1; for (int i = 2; i <= n; i++) { product = product * i; } return product; } // end factorial factorial: n factorial: product … … factorial: i Returns 120

6 6 Wright State University, College of Engineering Dr. T. Doom, Computer Science & Engineering CS 241 Computer Programming II Memory usage for recursive n! l Consider calling factorial(5) l Recursive implementation requires: –storage of 1 local/stack variables per frame –1 multiplication per call l Overall analysis? –Memory: O(n) –Time: O(n) factorial(5): n factorial(4): n … … factorial(3): n factorial(2): n factorial(1): n public int factorial (int n) { if (n <= 1) { // base case return 1; } else { // recursive step return (n * factorial (n-1)); } } // end factorial Returns 1 2 6 24 120

7 7 Wright State University, College of Engineering Dr. T. Doom, Computer Science & Engineering CS 241 Computer Programming II Recursion: The basics l A recursive method is one that calls itself –Recursive methods use a divide and conquer decomposition where one or more of the decomposed subcases are a smaller example of the main case –If this continues infinitely, then you’ll get a stack overflow –Thus recursive methods must also have one or more base cases in which they do not need to call themselves to provide a solution l Example: Searching for a name in the phone book –Start at middle –Are you one the right page? –Decide direction, ignore the portion of the book in the wrong direction –Repeat l What is the base case? What is the general decomposition?

8 8 Wright State University, College of Engineering Dr. T. Doom, Computer Science & Engineering CS 241 Computer Programming II Iterative paradigm l Expected number of comparisons In general: –Number in list: 8 O(n/2) –Number not in list: 16 O(n) public class Main { static int getIndexOfNumber (int searchNumber, int[] sortedList) { for (int i = 0; i < sortedList.length; i++ ){ if (sortedList[i] == searchNumber ) { return i; } return -1; // searchNumber not found in list } // end method getIndexOfNumber public static void main (String[] args) { int[] sortedNumberList = { 2, 15, 35, 67, 90, 102, 154, 256, 400, 900, 1024, 1300, 1301, 2000, 2005, 2006}; System.out.println(getIndexOfNumber(2000,sortedNumberList)); } // end method main } // end class Main

9 9 Wright State University, College of Engineering Dr. T. Doom, Computer Science & Engineering CS 241 Computer Programming II Iterative paradigm, improved l Expected number of comparisons In general: –Number in list: 8 + 1 O(n/2 + 1) –Number not in list: 8 + 1 O(n/2 + 1) … static int getIndexOfNumber (int searchNumber, int[] sortedList) { for (int i = 0; i < sortedList.length; i++ ){ if (sortedList[i] >= searchNumber ) { if (sortedList[i] == searchNumber) { return i; } else { return -1; // searchNumber not found in list } return -1; // searchNumber not found in list } // end method getIndexOfNumber …

10 10 Wright State University, College of Engineering Dr. T. Doom, Computer Science & Engineering CS 241 Computer Programming II Recursive paradigm l Expected number of comparisons In general: –Number in list: 4 + 1 O(log 2 n + 1) runtime –Number not in list: 4 + 1 O(log 2 n + 1) runtime static int getIndexOfNumberR (int searchNumber, int[] sortedList, int lowIndex, int highIndex) { int midIndex = (lowIndex + highIndex)/2; if (lowIndex == highIndex) { // base case if (searchNumber == sortedList[lowIndex]) { return lowIndex; } else { return -1; } int answer; if (searchNumber <= sortedList[midIndex]) { answer = getIndexOfNumberR(searchNumber,sortedList,lowIndex,midIndex); } else { answer = getIndexOfNumberR(searchNumber,sortedList,midIndex+1,highIndex); } return answer; } // end method getIndexOfNumber

11 11 Wright State University, College of Engineering Dr. T. Doom, Computer Science & Engineering CS 241 Computer Programming II College selector: a simple data structure l Decision Diagram can be implemented as a binary tree l Allows generic implementation l Defined recursively l Allows runtime change Like Math? Like design?Like kids? TrueFalse EngineeringSci/Math True False Fear needles? EducationNursing Want to be a suit? BusinessLiberal Arts True False

12 12 Wright State University, College of Engineering Dr. T. Doom, Computer Science & Engineering CS 241 Computer Programming II Code for a decision diagram / binary tree public class DecisionNode { String text; DecisionNode trueNode; DecisionNode falseNode; … } // end DecisionNode … DecisionNode enginering = new DecisionNode(“Engineering”,null,null); DecisionNode sciMath = new DecisionNode(“Sci/Math”,null,null); DecisionNode nursing = new DecisionNode(“Nursing”,null,null); DecisionNode education = new DecisionNode(“Education”,null,null); DecisionNode buisness = new DecisionNode(“Buisness”,null,null); DecisionNode liberalArts = new DecisionNode(“Liberal Arts”,null,null); DecisionNode question5 = new DecisionNode(“be suit?”, buisness, liberalArts); DecisionNode question4 = new DecisionNode(“fear needles?”, education, nursing); DecisionNode question3 = new DecisionNode(“like kids?”, question4, question5); DecisionNode question2 = new DecisionNode(“like design?”, sciMath, engineering); DecisionNode question1 = new DecisionNode(“like math?”, question2, question3); DecisionNode root = question1; … public DecisionNode (String text, DecisionNode trueNode, DecisionNode falseNode) { … } // end constructor

13 13 Wright State University, College of Engineering Dr. T. Doom, Computer Science & Engineering CS 241 Computer Programming II Recursive implementation l To process the whole tree, the method is called with a root node of the entire tree as an initial parameter. l The procedure calls itself recursively on the correct subtrees (based on the answer to the question) l until reaching the base case with no children (a "leaf"). public String getCollege (decisionNode root) { if ( (root.getTrueNode() == null) || (root.getfalseNode() == null)) { return decisionNode.getText(); } boolean answer = askQuestion(decisionNode.getText()); if (answer) { return getCollege (root.getTrueNode()) } else { return getCollege (root.getFalseNode()); } } // end getCollege

14 14 Wright State University, College of Engineering Dr. T. Doom, Computer Science & Engineering CS 241 Computer Programming II Counting the size of a binary tree public int countNodes (decisionNode root) { if ( (root.getTrueNode() == null) || (root.getFalseNode() == null) ) { return 1; } int trueSideCount = countNodes(root.getTrueNode()); int falseSideCount = countNodes(root.getFalseNode()); return 1 + trueSideCount + falseSideCount; } // end countNodes : 0,0 Shorthand : Each countNodes frame listed as root node, trueSideCount, falseSideCount : 0,0 : 0,0 : 1,0 : 0,0 : 1,0

15 15 Wright State University, College of Engineering Dr. T. Doom, Computer Science & Engineering CS 241 Computer Programming II Stack trace I : 0,0 Shorthand : Each countNodes frame listed as root node, trueSideCount, falseSideCount : 0,0 : 0,0 : 1,0 : 0,0 : 1,0 : 0,0 1,1 : 3,0 : 0,0 : 3,0 : 0,0 : 3,0 : 0,0 : 3,0 : 0,0 :1,0 : 3,0 : 0,0 :1,0 : 3,0 : 0,0 :1,1 : 3,0

16 16 Wright State University, College of Engineering Dr. T. Doom, Computer Science & Engineering CS 241 Computer Programming II Stack trace II Shorthand : Each countNodes frame listed as root node, trueSideCount, falseSideCount : 3,0 : 3,3 : 3,7 : 3,0 : 0,0 :1,0 : 3,0 : 0,0 :1,0 : 3,0 : 0,0 :1,1 : 3,0 :1,0 : 3,0 :0,0 : 3,0 :0,0 : 3,0 :1,0 : 3,0 :1,1 returns: 11

17 17 Wright State University, College of Engineering Dr. T. Doom, Computer Science & Engineering CS 241 Computer Programming II Final thoughts on recursion l We’ve already encountered many “recursive-like” programming features: –Constructor chaining –Serializing aggregate objects –Making deep copies l Thinking recursively takes time and practice –Recursive is not always better (usually not, in fact) –Recursive is sometimes simpler l In some instances a LOT simpler that –Recursive is sometimes more flexible

18 18 Wright State University, College of Engineering Dr. T. Doom, Computer Science & Engineering CS 241 Computer Programming II Suggested Practice: Fibonacci Sequence l Write a program that uses a static recursive method to return the n th number in a Fibonacci sequence. Recall that the n th number in the sequence depends upon the two previous numbers in the sequence. l Consider: –What is the base case? –What is the recursive case?


Download ppt "1 Wright State University, College of Engineering Dr. T. Doom, Computer Science & Engineering CS 241 Computer Programming II CS 241 – Computer Programming."

Similar presentations


Ads by Google