Topic 12 Introduction to Recursion

Slides:



Advertisements
Similar presentations
Introduction to Recursion and Recursive Algorithms
Advertisements

Recursion CS 367 – Introduction to Data Structures.
Tail Recursion. Problems with Recursion Recursion is generally favored over iteration in Scheme and many other languages – It’s elegant, minimal, can.
Recursion vs. Iteration The original Lisp language was truly a functional language: –Everything was expressed as functions –No local variables –No iteration.
Factorial Recursion stack Binary Search Towers of Hanoi
Fundamentals of Computer Science Lecture 14: Recursion Instructor: Evan Korth New York University.
Computer Science II Recursion Professor: Evan Korth New York University.
Recursion. Binary search example postponed to end of lecture.
Fundamentals of Computer Science Lecture 14: Recursion Instructor: Evan Korth New York University.
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 Road Map Introduction to Recursion Recursion Example #1: World’s Simplest Recursion Program Visualizing Recursion –Using Stacks Recursion Example.
Recursion.
Recursion A recursive function is a function that calls itself either directly or indirectly through another function. The problems that can be solved.
Topic 9 Introduction to Recursion
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.
Unit 181 Recursion Definition Recursive Methods Constructing Recursion Benefits and Usage Infinite Recursion Recursion Removal Examples Exercises.
Chapter 12 Recursion, Complexity, and Searching and Sorting
Chapter 7 Recursion Recursive methods Recursion in two- dimensional grids Recursive helper method Analysis of recursive algorithms.
Stephen P. Carl - CS 2421 Recursion Reading : Chapter 4.
1 CS 177 Week 16 Recitation Recursion. 2 Objective To understand and be able to program recursively by breaking down a problem into sub problems and joining.
Computer Science Department Data Structure & Algorithms Lecture 8 Recursion.
Review Introduction to Searching External and Internal Searching Types of Searching Linear or sequential search Binary Search Algorithms for Linear Search.
Chapter 8 Recursion Modified.
1 TCSS 143, Autumn 2004 Lecture Notes Recursion Koffman/Wolfgang Ch. 7, pp ,
Recursion. What is recursion? Rules of recursion Mathematical induction The Fibonacci sequence Summary Outline.
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.
Recursion Unit 15. Recursion: Recursion is defined as the process of a subprogram calling itself as part of the solution to a problem. It is a problem.
1 Recursion Recursion is a powerful programming technique that provides elegant solutions to certain problems. Chapter 11 focuses on explaining the underlying.
1 Recursion Recursive function: a function that calls itself (directly or indirectly). Recursion is often a good alternative to iteration (loops). Its.
CSE 143 Lecture 9: introduction to recursion reading: 12.1.
Building Java Programs Chapter 12: Recursive public/private pairs Chapter 13: Searching reading: 13.3.
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.
Recursion ITFN The Stack. A data structure maintained by each program at runtime. Push Pop.
CMSC201 Computer Science I for Majors Lecture 19 – Recursion
Recursion.
Chapter 13 Recursion Copyright © 2016 Pearson, Inc. All rights reserved.
Chapter 8: Recursion Data Structures in Java: From Abstract Data Types to the Java Collections Framework by Simon Gray.
Recursion CENG 707.
Recursion CENG 707.
to understand recursion you must understand recursion
Chapter 15 Recursion.
Introduction to Recursion
Introduction to Recursion
Recursion DRILL: Please take out your notes on Recursion
Searching – Linear and Binary Searches
Chapter 15 Recursion.
CMSC201 Computer Science I for Majors Lecture 18 – Recursion
Recursion
Data Structures Recursion CIS265/506: Chapter 06 - Recursion.
Java Software Structures: John Lewis & Joseph Chase
Building Java Programs
Recursion Great fleas have little fleas upon their backs to bite 'em, And little fleas have lesser fleas, and so ad infinitum. And the great fleas themselves,
CMSC201 Computer Science I for Majors Lecture 16 – Recursion
Recursion "To understand recursion, one must first understand recursion." -Stephen Hawking.
Topic 14 Searching and Simple Sorts
Building Java Programs
Recursion Data Structures.
CMSC201 Computer Science I for Majors Lecture 19 – Recursion
This Lecture Substitution model
Building Java Programs
RECURSION Annie Calpe
Topic 14 Searching and Simple Sorts
CS302 - Data Structures using C++
Yan Shi CS/SE 2630 Lecture Notes
This Lecture Substitution model
CS210- Lecture 3 Jun 6, 2005 Announcements
Chapter 13 Recursion Copyright © 2010 Pearson Addison-Wesley. All rights reserved.
Recursion.
Presentation transcript:

Topic 12 Introduction to Recursion "To a man with a hammer, everything looks like a nail" -Mark Twain

Underneath the Hood.

The Program Stack When you invoke a method in your code what happens when that method is completed? public static void start() { int x = 5; int y = -5; Point pt = new Point(x, y); pt.scale(2); String s = pt.toString(); } CS314 Recursion

Point Class public class Point { private int x; private int y; 100 public Point(int x, int y) { 101 this.x = x; 102 this.y = y; } 103 public void scale(int v) { 104 x *= v; 105 y *= v; } 106 public int getX() {return x;} 107 public int getY() {return y;} 108 public String toString() { 109 return "x: " + getX() + ", y: " + getY(); CS314 Recursion

The Program Stack When your program is executed on a processor the commands are converted into another set of instructions and assigned memory locations. normally a great deal of expansion takes place public static void start() { int x = 5; // 50 int y = -5; // 51 Point pt = new Point(x, y);// 52 pt.scale(2); //53 String s = pt.toString(); // 54 } CS314 Recursion

Basic CPU Operations A CPU works via a fetch command / execute command loop and a program counter Instructions stored in memory (Instructions are data!) 50 int x = 5; 51 int y = -5; 52 Point pt = new Point(x, y); 53 pt.scale(2); 54 String s = pt.toString(); What if the first instruction of the scale method is stored at memory location 103? CS314 Recursion

More on the Program Stack 50 int x = 5; 51 int y = -5; 52 Point pt = new Point(x, y); 53 pt.scale(2); 54 String s = pt.toString(); Instruction 53 is really saying jump to instruction 103 with pt as the implicit parameter and 2 as the explicit parameter In general when method scale is done what happens? Program ends B. goes to instruction 54 C. Goes back to whatever method called it CS314 Recursion

Activation Records and the Program Stack When a method is invoked all the relevant information about the current method (variables, values of variables, next line of code to be executed) is placed in an activation record The activation record is pushed onto the program stack A stack is a data structure with a single access point, the top. CS314 Recursion

The Program Stack Data may either be added (pushed) or removed (popped) from a stack but it is always from the top. A stack of dishes which dish do we have easy access to? top CS314 Recursion

Using Recursion

A Problem Write a method that determines how much space is take up by the files in a directory A directory can contain files and directories How many directories does our code have to examine? How would you add up the space taken up by the files in a single directory Hint: don't worry about any sub directories at first CS314 Recursion

Attendance Question 2 How many levels of directories have to be visited? Unknown Infinite 1 8 CS314 Recursion

Sample Directory Structure scottm AP cs307 m1.txt m2.txt A.pdf AB.pdf hw a1.htm a2.htm a3.htm a4.htm CS314 Recursion

Java File Class File(String pathname) Creates a new File instance by converting the given pathname. boolean isDirectory() Tests whether the file denoted by this abstract pathname is a directory. File[] listFiles() Returns an array of abstract pathnames denoting the files in the directory denoted by this abstract pathname. CS314 Recursion

Code for getDirectorySpace() // assert dir is a directory and dir != null public static long spaceUsed(File dir) { assert dir != null && dir.isDirectory(); long spaceUsed = 0; File[] subFilesAndDirs = dir.listFiles(); if(subFilesAndDirs != null) for(File sub : subFilesAndDirs) if(sub != null) if(!sub.isDirectory()) // sub is a plain old file spaceUsed += sub.length(); else // else sub is a directory spaceUsed += spaceUsed(sub); return spaceUsed; } CS314 Recursion

Attendance Question 3 Is it possible to write a non recursive method to do this (determine space taken up by files in a directory, including its subdirectories, and their subdirectories, and their subdirectories, and so forth)? Yes No CS314 Recursion

Iterative getDirectorySpace() public int getDirectorySpace(Directory d) { ArrayList dirs = new ArrayList(); File[] fileList; Directory[] dirList; dirs.add(d); Directory temp; int total = 0; while( ! dirs.isEmpty() ) { temp = (Directory)dirs.remove(0); fileList = temp.getFiles(); for(int i = 0; i < fileList.length; i++) total += fileList[i].getSize(); dirList = temp.getSubdirectories(); for(int i =0; i < dirList.length; i++) dirs.add( dirList[i] ); } return total; CS314 Recursion

Wisdom for Writing Recursive Methods

The 3 plus 1 rules of Recursion Know when to stop Decide how to take one step Break the journey down into that step and a smaller journey Have faith From Common Lisp: A Gentle Introduction to Symbolic Computation by David Touretzky CS314 Recursion

Writing Recursive Methods Rules of Recursion Base Case: Always have at least one case that can be solved without using recursion Make Progress: Any recursive call must progress toward a base case. "You gotta believe." Always assume that the recursive call works. (Of course you will have to design it and test it to see if it works or prove that it always works.) A recursive solution solves a small part of the problem and leaves the rest of the problem in the same form as the original CS314 Recursion

N! the classic first recursion problem / example N! 5! = 5 * 4 * 3 * 2 * 1 = 120 int res = 1; for(int i = 2; i <= n; i++) res *= i; CS314 Recursion

Factorial Recursively Mathematical Definition of Factorial 0! = 1 N! = N * (N - 1)! The definition is recursive. // pre n >= 0 public int fact(int n) { if(n == 0) return 1; else return n * fact(n-1); } CS314 Recursion

Tracing Fact With the Program Stack System.out.println( fact(4) ); top System.out.println( fact(4) ); CS314 Recursion

Calling fact with 4 4 in method fact n top partial result = n * fact(n-1) top System.out.println( fact(4) ); CS314 Recursion

Calling fact with 3 3 in method fact n 4 in method fact n top partial result = n * fact(n-1) 4 in method fact n top partial result = n * fact(n-1) System.out.println( fact(4) ); CS314 Recursion

Calling fact with 2 2 in method fact n 3 in method fact n top 4 partial result = n * fact(n-1) 3 in method fact n top partial result = n * fact(n-1) 4 in method fact n partial result = n * fact(n-1) System.out.println( fact(4) ); CS314 Recursion

Calling fact with 1 1 in method fact n 2 in method fact n top 3 partial result = n * fact(n-1) 2 in method fact n top partial result = n * fact(n-1) 3 in method fact n partial result = n * fact(n-1) 4 in method fact n partial result = n * fact(n-1) System.out.println( fact(4) ); CS314 Recursion

Calling fact with 0 and returning 1 in method fact n returning 1 to whatever method called me 1 in method fact n top partial result = n * fact(n-1) 2 in method fact n partial result = n * fact(n-1) 3 in method fact n partial result = n * fact(n-1) 4 in method fact n partial result = n * fact(n-1) CS314 Recursion System.out.println( fact(4) );

Returning 1 from fact(1) n 1 in method fact 2 in method fact top n 3 partial result = n * 1, return 1 to whatever method called me 2 in method fact top n partial result = n * fact(n-1) 3 in method fact n partial result = n * fact(n-1) 4 in method fact n partial result = n * fact(n-1) System.out.println( fact(4) ); CS314 Recursion

Returning 2 from fact(2) 2 in method fact n 3 in method fact n top 4 partial result = 2 * 1, return 2 to whatever method called me 3 in method fact n top partial result = n * fact(n-1) 4 in method fact n partial result = n * fact(n-1) System.out.println( fact(4) ); CS314 Recursion

Returning 6 from fact(3) 3 in method fact n 4 in method fact n top partial result = 3 * 2, return 6 to whatever method called me 4 in method fact n top partial result = n * fact(n-1) System.out.println( fact(4) ); CS314 Recursion

Returning 24 from fact(4) 4 in method fact n top partial result = 4 * 6, return 24 to whatever method called me top System.out.println( fact(4) ); CS314 Recursion

Calling System.out.println top ?? CS314 Recursion

Evaluating Recursive Methods

Evaluating Recursive Methods you must be able to evaluate recursive methods public static int mystery (int n){ if( n == 0 ) return 1; else return 3 * mystery(n-1); } // what is returned by mystery(5) CS314 Recursion

Evaluating Recursive Methods Draw the program stack! with practice you can see the result m(5) = 3 * m(4) m(4) = 3 * m(3) m(3) = 3 * m(2) m(2) = 3 * m(1) m(1) = 3 * m(0) m(0) = 1 -> 3^5 = 243 CS314 Recursion

Attendance Question 4 What is returned by mystery(-3) ? 1 1 Infinite loop Syntax error Runtime error CS314 Recursion

Evaluating Recursive Methods What about multiple recursive calls? public static int bar(int n){ if( n <= 0 ) return 2; else return 3 + bar(n-1) + bar(n-2); } What does bar(5) return? A. 2 B. 5 C. 13 D. 62 E. 127 CS314 Recursion

Evaluating Recursive Methods What is returned by bar(5)? b(5) = 3 + b(4) + b(3) b(4) = 3 + b(3) + b(2) b(3) = 3 + b(2) + b(1) b(2) = 3 + b(1) + b(0) b(1) = 3 + b(0) + b(-1) b(0) = 2 b(-1) = 2 CS314 Recursion

Evaluating Recursive Methods What is returned by bar(5)? b(5) = 3 + b(4) + b(3) b(4) = 3 + b(3) + b(2) b(3) = 3 + b(2) + b(1) b(2) = 3 + b(1) + b(0) //substitute in results b(1) = 3 + 2 + 2 = 7 b(0) = 2 b(-1) = 2 CS314 Recursion

Evaluating Recursive Methods What is returned by bar(5)? b(5) = 3 + b(4) + b(3) b(4) = 3 + b(3) + b(2) b(3) = 3 + b(2) + b(1) b(2) = 3 + 7 + 2 =12 b(1) = 7 b(0) = 2 b(-1) = 2 CS314 Recursion

Evaluating Recursive Methods What is returned by bar(5)? b(5) = 3 + b(4) + b(3) b(4) = 3 + b(3) + b(2) b(3) = 3 + 12 + 7 = 22 b(2) = 12 b(1) = 7 b(0) = 2 b(-1) = 2 CS314 Recursion

Evaluating Recursive Methods What is returned by bar(5)? b(5) = 3 + b(4) + b(3) b(4) = 3 + 22 + 12 = 37 b(3) = 22 b(2) = 12 b(1) = 7 b(0) = 2 b(-1) = 2 CS314 Recursion

Evaluating Recursive Methods What is returned by bar(5)? b(5) = 3 + 37 + 22 = 62 b(4) = 37 b(3) = 22 b(2) = 12 b(1) = 7 b(0) = 2 b(-1) = 2 CS314 Recursion

Recursion Practice Write a method raiseToPower(int base, int power) //pre: power >= 0 Simple recursion (also called tail recursion) CS314 Recursion

Finding the Maximum in an Array public int max(int[] values){ Helper method or create smaller arrays each time CS314 Recursion

Attendance Question 5 When writing recursive methods what should be done first? Determine recursive case Determine recursive step Make recursive call Determine base case(s) Determine Big O CS314 Recursion

Your Meta Cognitive State Remember we are learning to use a tool. It is not a good tool for all problems. In fact we will implement several algorithms and methods where an iterative (looping without recursion) solution would work just fine After learning the mechanics and basics of recursion the real skill is knowing what problems or class of problems to apply it to CS314 Recursion

Big O and Recursion Determining the Big O of recursive methods can be tricky. A recurrence relation exits if the function is defined recursively. The T(N), actual running time, for N! is recursive T(N)fact = T(N-1)fact + O(1) This turns out to be O(N) There are N steps involved CS314 Recursion

Common Recurrence Relations T(N) = T(N/2) + O(1) -> O(logN) binary search T(N) = T(N-1) + O(1) -> O(N) sequential search, factorial T(N) = T(N/2) + T(N/2) + O(1) -> O(N), tree traversal T(N) = T(N-1) + O(N) -> O(N^2) selection sort T(N) = T(N/2) + T(N/2) + O(N) -> O(NlogN) merge sort T(N) = T(N-1) + T(N-1) + O(1) -> O(2^N) Fibonacci CS314 Recursion