1 / 16

Department of Computer and Information Science, School of Science, IUPUI

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 IUPUI droberts@cs.iupui.edu. Why Recursion?. If sequence, ifs, and loops are enough, why recursion?

tamar
Download Presentation

Department of Computer and Information Science, School of Science, IUPUI

An Image/Link below is provided (as is) to download presentation Download Policy: Content on the Website is provided to you AS IS for your information and personal use and may not be sold / licensed / shared on other websites without getting consent from its author. Content is provided to you AS IS for your information and personal use only. Download presentation by click this link. While downloading, if for some reason you are not able to download a presentation, the publisher may have deleted the file from their server. During download, if you can't get a presentation, the file might be deleted by the publisher.

E N D

Presentation Transcript


  1. 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 IUPUI droberts@cs.iupui.edu

  2. Why Recursion? If sequence, ifs, and loops are 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!

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

  4. 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! = 1n! = n* (n-1)!where n is not negative. Base Case Recursive Case

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

  6. 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 Dive Phase Surface Phase Maximum Depth = 5

  7. A simple definition of recursion • Recursion simply means a function that calls itself. • 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.)

  8. Questionable Recursive Program int puzzle(int N) { if (N == 1) return 1; if (N % 2 == 0) return puzzle(N/2); else 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

  9. Sample Recursive Program: Euclid’s Greatest Common Divisor int gcd(int m, int n) { if (n == 0) return m; return gcd(n, m % n); } Sedgewick Program 5.3

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

  11. Sample Recursive Program: Linked List (cont) void traverseR(link h, void (*visit)(link)) { if (h == NULL) return; traverseR(h->next, visit); (*visit)(h); } link delete(link x, Item v) { /* Delete 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; } x->next = delete(x->next, v); return x; } Sedgewick Program 5.5

  12. 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?

  13. 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?

  14. Implementation of Directory Search using System; using System.IO; namespace RecursiveDirectoryFileSearch { class RecursiveDirectoryFileSearch { static void main(string[] args) { Console.WriteLine("Found {0} occurrences.", iDirectorySearch(@"C:\","*.tmp")); Console.WriteLine( "Press enter to continue"); Console.ReadLine(); } } } This implementation is in C#.

  15. Implementation of Directory Search (cont) // <returns> Number of files found that match the pattern</returns> 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

  16. Acknowledgements • Robert Sedgewick. Algorithms in C.

More Related