Dale Roberts Department of Computer and Information Science, School of Science, IUPUI CSCI 240 Review of Recursion For those of you that have slept since.

Slides:



Advertisements
Similar presentations
Introduction to Computer Science Robert Sedgewick and Kevin Wayne Recursive Factorial Demo pubic class Factorial {
Advertisements

Main Index Contents 11 Main Index Contents Week 6 – Binary Trees.
Fundamentals of Computer Science Lecture 14: Recursion Instructor: Evan Korth New York University.
ITEC200 – Week07 Recursion. 2 Learning Objectives – Week07 Recursion (Ch 07) Students can: Design recursive algorithms to solve.
Circular Arrays Neat trick: use a circular array to insert and remove items from a queue in constant time The idea of a circular array is that the end.
Computer Science II Recursion Professor: Evan Korth New York University.
Recursion. Idea: Some problems can be broken down into smaller versions of the same problem Example: n! 1*2*3*…*(n-1)*n n*factorial of (n-1)
1 Recursion Overview l Introduction to recursion and recursive methods l Simple popular recursive algorithms l Writing recursive methods l Preview: Parameter.
Main Index Contents 11 Main Index Contents Tree StructuresTree Structures (3 slides) Tree Structures Tree Node Level and Path Len. Tree Node Level and.
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.
1 Introduction to Recursion  Introduction to Recursion  Example 1: Factorial  Example 2: Reversing Strings  Example 3: Fibonacci  Infinite Recursion.
1 CSCD 300 Data Structures Recursion. 2 Proof by Induction Introduction only - topic will be covered in detail in CS 320 Prove: N   i = N ( N + 1.
Recursion. 2 CMPS 12B, UC Santa Cruz Solving problems by recursion How can you solve a complex problem? Devise a complex solution Break the complex problem.
Recursion Road Map Introduction to Recursion Recursion Example #1: World’s Simplest Recursion Program Visualizing Recursion –Using Stacks Recursion Example.
1 Recursion Recursive Thinking Recursive Programming Recursion versus Iteration Direct versus Indirect Recursion More on Project 2 Reading L&C 10.1 – 10.4.
CS 146: Data Structures and Algorithms June 18 Class Meeting Department of Computer Science San Jose State University Summer 2015 Instructor: Ron Mak
Lecture Objectives  To learn how to use a tree to represent a hierarchical organization of information  To learn how to use recursion to process trees.
A Review of Recursion Dr. Jicheng Fu Department of Computer Science University of Central Oklahoma.
Thought for the Day “To become truly great, one has to stand with people, not above them.” – Charles de Montesquieu.
Chapter 13 Recursion. Topics Simple Recursion Recursion with a Return Value Recursion with Two Base Cases Binary Search Revisited Animation Using Recursion.
Advance Data Structure and Algorithm COSC600 Dr. Yanggon Kim Chapter 1.
CS-2852 Data Structures LECTURE 12B Andrew J. Wozniewicz Image copyright © 2010 andyjphoto.com.
M180: Data Structures & Algorithms in Java
Analyzing Complexity of Lists OperationSorted Array Sorted Linked List Unsorted Array Unsorted Linked List Search( L, x ) O(logn) O( n ) O( n ) Insert(
Computer Science Department Data Structure & Algorithms Lecture 8 Recursion.
1 C++ Classes and Data Structures Jeffrey S. Childs Chapter 13 Recursion Jeffrey S. Childs Clarion University of PA © 2008, Prentice Hall.
Hopefully this lesson will give you an inception of what recursion is.
Chapter 8 Recursion Modified.
Dale Roberts Department of Computer and Information Science, School of Science, IUPUI CSCI 240 Trees Dale Roberts, Lecturer
Dale Roberts CSCI N305 Functions Recursion Department of Computer and Information Science, School of Science, IUPUI.
Recursion. Math Review Given the following sequence: a 1 = 1 a n = 2*a n-1 OR a n+1 = 2*a n What are the values of the following? a 2 = a 3 = a 4 =
Liang, Introduction to Java Programming, Tenth Edition, (c) 2013 Pearson Education, Inc. All rights reserved. 1 Chapter 18 Recursion Lecture 6 Dr. Musab.
Dale Roberts Department of Computer and Information Science, School of Science, IUPUI CSCI 240 Review of Recursion For those of you that have slept since.
1 CompSci 105 SS 2005 Principles of Computer Science Lecture 6: Recursion Lecturer: Santokh Singh Assignment 1 due tomorrow. Should have started working.
Data Structure and Algorithms. Algorithms: efficiency and complexity Recursion Reading Algorithms.
Dale Roberts Department of Computer and Information Science, School of Science, IUPUI CSCI 240 Recursion and Trees Dale Roberts, Lecturer
Dale Roberts Department of Computer and Information Science, School of Science, IUPUI CSCI 230 Data Structures Dale Roberts, Lecturer Computer Science,
Binary Trees In computer science, a binary tree is a tree data structure in which each node has at most two children, which are referred to as the left.
1 Recursion Recursive Thinking Recursive Programming Recursion versus Iteration Direct versus Indirect Recursion Reading L&C 3 rd : 7.1 – nd :
Dale Roberts Department of Computer and Information Science, School of Science, IUPUI CSCI 230 Dale Roberts, Lecturer Data Structure.
Int fact (int n) { If (n == 0) return 1; else return n * fact (n – 1); } 5 void main () { Int Sum; : Sum = fact (5); : } Factorial Program Using Recursion.
Chapter 7 Trees_ Part2 TREES. Depth and Height 2  Let v be a node of a tree T. The depth of v is the number of ancestors of v, excluding v itself. 
CS 116 Object Oriented Programming II Lecture 13 Acknowledgement: Contains materials provided by George Koutsogiannakis and Matt Bauer.
Program Development and Design Using C++, Third Edition
1 CSC 143 Recursion [Reading: Chapter 17]. 2 Recursion  A recursive definition is one which is defined in terms of itself.  Example:  Sum of the first.
Trees and Graphs CSE 2320 – Algorithms and Data Structures Vassilis Athitsos University of Texas at Arlington 1.
Recursion CSE 2320 – Algorithms and Data Structures
Topic 6 Recursion.
Chapter 15 Recursion.
Introduction to Recursion
Introduction to Recursion
Lecture No.13 Data Structures Dr. Sohail Aslam
Chapter 15 Recursion.
Trees CSE 2320 – Algorithms and Data Structures Vassilis Athitsos
Week 6 - Wednesday CS221.
Review: recursion Tree traversals
Recursion CSE 2320 – Algorithms and Data Structures
Recursive Thinking Chapter 9 introduces the technique of recursive programming. As you have seen, recursive programming involves spotting smaller occurrences.
Recursion Chapter 10.
Recursive Thinking Chapter 9 introduces the technique of recursive programming. As you have seen, recursive programming involves spotting smaller occurrences.
Recursion "To understand recursion, one must first understand recursion." -Stephen Hawking.
Recursion Recursive Thinking Recursive Programming
Functions Recursion CSCI 230
Trees (part 2) CSE 2320 – Algorithms and Data Structures
Recursion Chapter 18.
Chapter 10 1 – Binary Trees Tree Structures (3 slides)
Recursion.
Dr. Sampath Jayarathna Cal Poly Pomona
Recursive Thinking.
Presentation transcript:

Dale Roberts Department of Computer and Information Science, School of Science, IUPUI CSCI 240 Review of Recursion For those of you that have slept since then… Dale Roberts, Lecturer

Dale Roberts Why Recursion? If if’s, loop’s, and sequence is enough, why recursion? Subset of looping problems, where the problem breaks down into identical pieces We will use a series of problems with straightforward recursive solutions to motivate our discussion. Practical example? Directory Search!

Dale Roberts Introduction to Recursion Problem based approach A simple example: factorial Simple definition of recursion Bridges: Parallels with looping See if you can do it: GCF A realistic example: Directory Search Conclusion

Dale Roberts Simple Example: Factorial An easy first example is to consider the problem of implementing a function that calculates a factorial. Recall from math that factorial is defined as 0! = 1 n! = n* (n-1)! where n is not negative. Base Case Recursive Case

Dale Roberts Implementation int factorial(int N) { if (N == 0) if (N == 0) return 1; return 1; return N*factorial(N-1); return N*factorial(N-1);} Base Case Recursive Case Sedgewick Program 5.1

Dale Roberts Factorial Sample Execution iFactorial(4): 4*iFactorial(3) iFactorial(3): 3*iFactorial(2) iFactorial(2): 2*iFactorial(1) iFactorial(1): 1*iFactorial(0) iFactorial(0): 1 iFactorial(4): 4*6 = 24 iFactorial(3): 3*2 = 6 iFactorial(2): 2*1 = 2 iFactorial(1): 1*1 = 1 iFactorial(0): 1 Surface Phase Dive Phase Maximum Depth = 5

Dale Roberts A simple definition of recursion Recursion simply means a function that calls itself. The conditions that cause a function to call itself again are called the recursive case. In order to keep the recursion from going on forever, you must make sure you hit a termination condition called the base case. The number of nested invocations is called the depth of recursion. Function may call itself directly or indirectly. (All of our examples are direct.)

Dale Roberts Fundamental Rules of Recursion Obeys 1.) Base cases 2.) Making progress through recursion 3.) Design rule: assuming all recursive call work (details hidden) 4.) Compound interest rule: do not duplicate recursive calls Always specify the base case; otherwise, indefinite recursive will occur and cause “stack-overflow” error.

Dale Roberts Questionable Recursive Program int puzzle(int N) { if (N == 1) if (N == 1) return 1; return 1; if (N % 2 == 0) if (N % 2 == 0) return puzzle(N/2); return puzzle(N/2); else else return puzzle(3*N+1); return puzzle(3*N+1);} What’s Makes this Program Questionable? This recursive call is not smaller than the original. Cannot prove it terminates. But it does…. Sedgewick Program 5.2

Dale Roberts Sample Recursive Program: Euclid’s Greatest Common Factor int gcf(int m, int n) { if (n == 0) if (n == 0) return m; return m; return gcf(n, m % n); return gcf(n, m % n);} Sedgewick Program 5.3

Dale Roberts Sample Recursive Program: Linked List int count(link x) { if (x == NULL) if (x == NULL) return 0; return 0; return 1 + count(x->next); return 1 + count(x->next);} void traverse(link h, void (*visit)(link)) { if (h == NULL) if (h == NULL) return; return; (*visit)(h); (*visit)(h); traverse(h->next, visit); traverse(h->next, visit);} Sedgewick Program 5.5

Dale Roberts Sample Recursive Program: Linked List (cont) void traverseR(link h, void (*visit)(link)) { if (h == NULL) return; if (h == NULL) return; traverseR(h->next, visit); traverseR(h->next, visit); (*visit)(h); (*visit)(h);} link delete(link x, Item v) { /* Deleted a nodes, and returns remainder of list */ if (x == NULL) return NULL; if (eq(x->item, v)) { link t = x->next; free(x); return t; } { link t = x->next; free(x); return t; } x->next = delete(x->next, v); return x; } Sedgewick Program 5.5

Dale Roberts Sample recursive programs (Tree Traversal) In-order: (LNR) void inorder(tree_pointer ptr) { if (ptr) if (ptr) { inorder(ptr->left_child); inorder(ptr->left_child); printf(“%d”, ptr->data); printf(“%d”, ptr->data); inorder(ptr->right_child); inorder(ptr->right_child); }} Pre-order: (NLR) void preorder(tree_pointer ptr) { if (ptr) if (ptr) { printf(“%d”, ptr->data); printf(“%d”, ptr->data); preorder(ptr->left_child); preorder(ptr->left_child); preorder(ptr->right_child); preorder(ptr->right_child); }} Post-order: (LRN) void postorder(tree_pointer ptr) { if (ptr) if (ptr) { postorder(ptr->left_child); postorder(ptr->left_child); postorder(ptr->right_child); postorder(ptr->right_child); printf(“%d”, ptr->data); printf(“%d”, ptr->data); }}

Dale Roberts Building Bridges: Looping Recursion and looping follow similar thought processes. A loop’s termination condition serves the same role as a recursive base case. A loop’s control variable serves the same role as a general case. sum = 0; i = 1; while (i <= 10) { sum += i; i++; } int iFactorial(int n) { if (n == 0) // base case { return 1; } else // n > 0, recursive case { return n*iFactorial(n-1); } Termination Condition Loop control and recursive case both move toward termination condition What happens if loop control and recursive case does not move toward termination condition?

Dale Roberts Realistic Example: Directory Searching A more common example of recursion is searching through a hard disk directory structure. Analysis: Directories are made up of files and subdirectories. Process the files within a directory, and then process each if its subdirectories recursively. Count the number of files that match the search pattern. What is the base case? What is the recursive case? What is the maximum depth of recursion? How many *.tmp files do you think are on your C: drive?

Dale Roberts Implementation of Directory Search using System; using System.IO; namespace RecursiveDirectoryFileSearch { class RecursiveDirectoryFileSearch { static void Main(string[] args) { Console.WriteLine("Found {0} occurrences.", Console.WriteLine( "Press enter to continue"); Console.ReadLine(); } This implementation is in C#.

Dale Roberts Implementation of Directory Search (cont) // Number of files found that match the pattern internal static int iDirectorySearch( string asDirectory, string asSearchPattern) { // Local variables int liFileCounter = 0; // Process each file foreach (string lsFileName in Directory.GetFiles(asDirectory, asSearchPattern)) { Console.WriteLine(lsFileName); liFileCounter++; } // Process each subdirectory foreach (string lsSubdirectory in Directory.GetDirectories(asDirectory)) { liFileCounter += iDirectorySearch(lsSubdirectory, ssSearchPattern); } return liFileCounter; } Base Case Recursive Case

Dale Roberts Acknowledgements Robert Sedgewick. Algorithms in C.