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

Slides:



Advertisements
Similar presentations
Basics of Recursion Programming with Recursion
Advertisements

Introduction to Algorithms Quicksort
Introduction to Recursion and Recursive Algorithms
Recursion Ellen Walker CPSC 201 Data Structures Hiram College.
Fundamentals of Computer Science Lecture 14: Recursion Instructor: Evan Korth New York University.
1 Chapter 11 l Basics of Recursion l Programming with Recursion Recursion.
ITEC200 – Week07 Recursion. 2 Learning Objectives – Week07 Recursion (Ch 07) Students can: Design recursive algorithms to solve.
CS 106 Introduction to Computer Science I 11 / 09 / 2007 Instructor: Michael Eckmann.
Search and Recursion pt. 2 CS221 – 2/25/09. How to Implement Binary Search Take a sorted data-set to search and a key to search for Start at the mid-point.
Computer Science II Recursion Professor: Evan Korth New York University.
Lesson 19 Recursion CS1 -- John Cole1. Recursion 1. (n) The act of cursing again. 2. see recursion 3. The concept of functions which can call themselves.
Fundamentals of Computer Science Lecture 14: Recursion Instructor: Evan Korth New York University.
Unit 181 Recursion Definition Recursive Methods Example 1 How does Recursion work? Example 2 Problems with Recursion Infinite Recursion Exercises.
Slides prepared by Rose Williams, Binghamton University Chapter 11 Recursion.
Recursion. Objectives At the conclusion of this lesson, students should be able to Explain what recursion is Design and write functions that use recursion.
1 Introduction to Recursion  Introduction to Recursion  Example 1: Factorial  Example 2: Reversing Strings  Example 3: Fibonacci  Infinite Recursion.
Slides prepared by Rose Williams, Binghamton University Chapter 11 Recursion.
CS 206 Introduction to Computer Science II 10 / 14 / 2009 Instructor: Michael Eckmann.
Recursion Road Map Introduction to Recursion Recursion Example #1: World’s Simplest Recursion Program Visualizing Recursion –Using Stacks Recursion Example.
Chapter 11 Recursion Copyright © 2010 Pearson Addison-Wesley. All rights reserved.
CS 106 Introduction to Computer Science I 03 / 28 / 2008 Instructor: Michael Eckmann.
CS 106 Introduction to Computer Science I 03 / 30 / 2007 Instructor: Michael Eckmann.
Recursion Chapter 7. Chapter 7: Recursion2 Chapter Objectives To understand how to think recursively To learn how to trace a recursive method To learn.
CHAPTER 10 Recursion. 2 Recursive Thinking Recursion is a programming technique in which a method can call itself to solve a problem A recursive definition.
Prof. S.M. Lee Department of Computer Science. Answer:
Copyright © 2009 Pearson Education, Inc. Publishing as Pearson Addison-Wesley Chapter 19: Recursion.
A Review of Recursion Dr. Jicheng Fu Department of Computer Science University of Central Oklahoma.
Recursion Chapter 7 Copyright ©2012 by Pearson Education, Inc. All rights reserved.
1 Recursion Dr. Bernard Chen Ph.D. University of Central Arkansas.
Recursion. Basic problem solving technique is to divide a problem into smaller subproblems These subproblems may also be divided into smaller subproblems.
Lecture 8. How to Form Recursive relations 1. Recap Asymptotic analysis helps to highlight the order of growth of functions to compare algorithms Common.
A Computer Science Tapestry 1 Recursion (Tapestry 10.1, 10.3) l Recursion is an indispensable technique in a programming language ä Allows many complex.
Chapter 11 Recursion Slides prepared by Rose Williams, Binghamton University Copyright © 2008 Pearson Addison-Wesley. All rights reserved.
Recursion Chapter 7. Chapter Objectives  To understand how to think recursively  To learn how to trace a recursive method  To learn how to write recursive.
Chapter 12Java: an Introduction to Computer Science & Programming - Walter Savitch 1 Chapter 12 l Basics of Recursion l Programming with Recursion Recursion.
Chapter 11Java: an Introduction to Computer Science & Programming - Walter Savitch 1 Chapter 11 l Basics of Recursion l Programming with Recursion Recursion.
Chapter 9: Recursion1 CHAPTER 9 RECURSION. Recursion  Concept of recursion  A recursive: Benefit and Cost  Comparison : Iterative and recursive functions.
Chapter 12 Recursion, Complexity, and Searching and Sorting
Lecturer: Dr. AJ Bieszczad Chapter 11 COMP 150: Introduction to Object-Oriented Programming 11-1 l Basics of Recursion l Programming with Recursion Recursion.
Chapter 11Java: an Introduction to Computer Science & Programming - Walter Savitch 1 Chapter 11 l Basics of Recursion l Programming with Recursion Recursion.
Slides prepared by Rose Williams, Binghamton University ICS201 Lecture 19 : Recursion King Fahd University of Petroleum & Minerals College of Computer.
Computer Science Department Data Structure & Algorithms Lecture 8 Recursion.
Chapter 8 Recursion Modified.
Recursion. What is recursion? Rules of recursion Mathematical induction The Fibonacci sequence Summary Outline.
Dale Roberts CSCI N305 Functions Recursion Department of Computer and Information Science, School of Science, IUPUI.
Data Structures R e c u r s i o n. Recursive Thinking Recursion is a problem-solving approach that can be used to generate simple solutions to certain.
Java Programming: Guided Learning with Early Objects Chapter 11 Recursion.
IB Computer Science Unit 5 – Advanced Topics Recursion.
Chapter 11Java: an Introduction to Computer Science & Programming - Walter Savitch 1 Chapter 11 l Basics of Recursion l Programming with Recursion Recursion.
1 Recursion Recursion is a powerful programming technique that provides elegant solutions to certain problems. Chapter 11 focuses on explaining the underlying.
© Janice Regan, CMPT 128, February CMPT 128: Introduction to Computing Science for Engineering Students Recursion.
Recursion Chapter 17 Instructor: Scott Kristjanson CMPT 125/125 SFU Burnaby, Fall 2013.
1 Chapter 8 Recursion. 2 Recursive Function Call a recursion function is a function that either directly or indirectly makes a call to itself. but we.
1 Recursion Recursive function: a function that calls itself (directly or indirectly). Recursion is often a good alternative to iteration (loops). Its.
Recursion. Objectives At the conclusion of this lesson, students should be able to Explain what recursion is Design and write functions that use recursion.
CSC 143 P 1 CSC 143 Recursion [Chapter 5]. CSC 143 P 2 Recursion  A recursive definition is one which is defined in terms of itself  Example:  Compound.
CMSC201 Computer Science I for Majors Lecture 19 – Recursion
Chapter 19: Recursion.
Introduction to Recursion
Introduction to Recursion
Recursion DRILL: Please take out your notes on Recursion
Recursion A problem solving technique where an algorithm is defined in terms of itself A recursive method is a method that calls itself A recursive algorithm.
CMSC201 Computer Science I for Majors Lecture 18 – Recursion
To understand recursion, you have to understand recursion!
Java Software Structures: John Lewis & Joseph Chase
Recursion "To understand recursion, one must first understand recursion." -Stephen Hawking.
Applied Algorithms (Lecture 17) Recursion Fall-23
Chapter 12 Recursion (methods calling themselves)
Cs212: DataStructures Computer Science Department Lab 3 : Recursion.
Basics of Recursion Programming with Recursion
Presentation transcript:

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”.

Recursion Recursion - Recursion

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 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 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 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

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 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 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: O(n/2 + 1) –Number not in list: 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 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: O(log 2 n + 1) runtime –Number not in list: 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 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 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 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 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 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 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 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 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?