Using Recursion. Linear Recursion ( 4.1.1) Recall the Recursion Pattern ( 2.5) A Simple Example of Linear Recursion

Similar documents
Using Recursion Goodrich, Tamassia. Using Recursion 1

Data Structures and Algorithms " Recursion!

CSC 344 Algorithms and Complexity. What is Recursion?

Linked Lists. Outline. COMP9024: Data Structures and Algorithms. Algorithms versus Heuristics. Data Structures and Algorithms. Abstract Data Types

Recursion. The Recursion Pattern. Recursion 3/16/14

RECURSION (CH 5) A pattern for solving algorithm design problems

PDF created with pdffactory Pro trial version Recursion

Recursion Chapter 3.5

Data structure and algorithm in Python

NCS 301 DATA STRUCTURE USING C

8/19/2014. Most algorithms transform input objects into output objects The running time of an algorithm typically grows with input size

Algorithm Design and Recursion. Search and Sort Algorithms

Recursion. Chapter 7. Copyright 2012 by Pearson Education, Inc. All rights reserved

Discrete Mathematics Introduction

Announcements. Project 5 is on the street. Second part is essay questions for CoS teaming requirements.

Wentworth Institute of Technology COMP1050 Computer Science II Spring 2017 Derbinsky. Recursion. Lecture 13. Recursion

Recursion: Recursion: repeated curses

Recursion (Rosen, 6 th edition, Section 4.3, 4.4)

Q1 Q2 Q3 Q4 Q5 Total 1 * 7 1 * 5 20 * * Final marks Marks First Question

Chapter 12 Supplement: Recursion with Java 1.5. Mr. Dave Clausen La Cañada High School

We cover recursion in 150. Why do it again in 151?

ECE 2400 Computer Systems Programming Fall 2018 Topic 2: C Recursion

Lecture P6: Recursion

csci 210: Data Structures Stacks and Queues in Solution Searching

CSCE 110 Dr. Amr Goneid Exercise Sheet (7): Exercises on Recursion

CSCI-1200 Data Structures Spring 2018 Lecture 7 Order Notation & Basic Recursion

Algorithms 4. Odd or even Algorithm 5. Greatest among three numbers Algorithm 6. Simple Calculator Algorithm

Chapter 15: Recursion

Chapter 1: Number and Operations

Chapter Summary. Mathematical Induction Recursive Definitions Structural Induction Recursive Algorithms

Loops / Repetition Statements

Recursion CSCI 136: Fundamentals of Computer Science II Keith Vertanen Copyright 2011

CSC 273 Data Structures

Recursion. Overview. Mathematical induction. Hello recursion. Recursion. Example applications. Goal: Compute factorial N! = 1 * 2 * 3...

ECE264 Fall 2013 Exam 1, September 24, 2013

RECURSION (CONTINUED)

11.3 Function Prototypes

Fundamentals of Programming Session 13

Module 10. Recursion. Adapted from Absolute Java, Rose Williams, Binghamton University

CS61B Lecture #2. Public Service Announcements:

Lesson 12: Recursion, Complexity, Searching and Sorting. Modifications By Mr. Dave Clausen Updated for Java 1_5

Parallel Sorting Algorithms

1. (15 points) Solve the decanting problem for containers of sizes 199 and 179; that is find integers x and y satisfying.

Recursive Definitions

More Complicated Recursion CMPSC 122

CSCE 314 Programming Languages

Decision-Making and Repetition

Chapter 13 Recursion. Chapter Objectives

Types of Recursive Methods

Note: unless otherwise stated, the questions are with reference to the C Programming Language. You may use extra sheets if need be.

CS103L SPRING 2017 UNIT 8: RECURSION

Computer Science Foundation Exam. Dec. 19, 2003 COMPUTER SCIENCE I. Section I A. No Calculators! KEY

Lecture 6: Recursion RECURSION

6.001 Notes: Section 4.1

Chapter 5: Recursion. Objectives

Tail Recursion. ;; a recursive program for factorial (define fact (lambda (m) ;; m is non-negative (if (= m 0) 1 (* m (fact (- m 1))))))

CS 137 Part 8. Merge Sort, Quick Sort, Binary Search. November 20th, 2017

Recursion. Fundamentals of Computer Science

Announcements. Recursion and why study it. Recursive programming. Recursion basic idea

Recursion. Chapter 11. Chapter 11 1

142


Reduction & Recursion Overview

Logical Coding, algorithms and Data Structures

Algorithms. Chapter 8. Objectives After studying this chapter, students should be able to:

Functional programming with Common Lisp

EASY

Test Bank Ver. 5.0: Data Abstraction and Problem Solving with C++: Walls and Mirrors, 5 th edition, Frank M. Carrano

CMSC 132: Object-Oriented Programming II. Recursive Algorithms. Department of Computer Science University of Maryland, College Park

Programming II (CS300)

Chapter 5: Recursion

AP Programming - Chapter 17 Lecture page 1 of 5

Programming II (CS300)

34. Recursion. Java. Summer 2008 Instructor: Dr. Masoud Yaghini

Solutions to Assessment

Functions. CS10001: Programming & Data Structures. Sudeshna Sarkar Professor, Dept. of Computer Sc. & Engg., Indian Institute of Technology Kharagpur

This session. Recursion. Planning the development. Software development. COM1022 Functional Programming and Reasoning

RECURSION (CONTINUED)

CS1 Recitation. Week 2

Data Structures And Algorithms

Recursion defining an object (or function, algorithm, etc.) in terms of itself. Recursion can be used to define sequences

Loops. When to Use Loops

Recursion. Lecture 26 Sections , Robb T. Koether. Hampden-Sydney College. Mon, Apr 6, 2015

Recursion. What is Recursion? Simple Example. Repeatedly Reduce the Problem Into Smaller Problems to Solve the Big Problem

Chapter 7. Iteration. 7.1 Multiple assignment

Recursion vs Induction. CS3330: Algorithms The University of Iowa

Recursion. Comp Sci 1575 Data Structures. Introduction. Simple examples. The call stack. Types of recursion. Recursive programming

Computer Science E-119 Fall Problem Set 1. Due before lecture on Wednesday, September 26

Overview. What is recursion? When one function calls itself directly or indirectly.

e-pg PATHSHALA- Computer Science Design and Analysis of Algorithms Module 14 Component-I (A) - Personal Details

11/2/2017 RECURSION. Chapter 5. Recursive Thinking. Section 5.1

Algorithmic Analysis. Go go Big O(h)!

Classic Data Structures Introduction UNIT I

! Determine if a number is odd or even. ! Determine if a number/character is in a range. - 1 to 10 (inclusive) - between a and z (inclusive)

Beyond Counting. Owen Kaser. September 17, 2014

Recursive Thinking. Chapter 8: Recursion. Recursive Definitions. Recursion. Java Software Solutions for AP* Computer Science A 2nd Edition

Stack. Data structure with Last-In First-Out (LIFO) behavior. Out

The University of Nottingham

Recursion. EECS2030: Advanced Object Oriented Programming Fall 2017 CHEN-WEI WANG

8 Algorithms 8.1. Foundations of Computer Science Cengage Learning

Transcription:

Using Recursion Re the Recursion Pattern ( 2.5) Recursion: when a method s itself Classic example- - the factorial function: n! = 1 2 3 (n-1) n Recursive definition: Using Recursion 1 As a Java method: // recursive factorial function public static int recursivefactorial(int n) { if (n == 0) return 1; // basis case return n * recursivefactorial(n- 1); // recursive case f ( n) = n f ( n 1) if n = 0 Using Recursion 2 Linear Recursion ( 4.1.1) Test for base cases. Begin by testing for a set of base cases (there should be at least one). Every possible chain of recursive s must eventually reach a base case, and the handling of each base case should not use recursion. Recur once. Perform a single recursive. (This recursive step may involve a test that decides which of several possible recursive s to make, but it should ultimately choose to make just one of these s each time we perform this step.) Define each possible recursive so that it makes progress towards a base case. Using Recursion 3 A Simple Example of Linear Recursion Algorithm LinearSum(A, n): Input: A integer array A and an integer n = 1, such that A has at least n elements Output: The sum of the first n integers in A if n = 1 then return A[0] return LinearSum(A, n - 1) + A[n -1] Example recursion trace: return 15 + A[4] = 15 + 5 = 20 LinearSum(A,5) LinearSum(A,4) LinearSum(A,3) LinearSum(A,2) LinearSum(A,1) return 13 + A[3] = 13 + 2 = 15 return 7 + A[2] = 7 + 6 = 13 return 4 + A[1] = 4 + 3 = 7 return A[0] = 4 Using Recursion 4

Reversing an Array Algorithm ReverseArray(A, i, j): Input: An array A and nonnegative integer indices i and j Output: The reversal of the elements in A starting at index i and ending at j if i < j then Swap A[i] and A[ j] ReverseArray(A, i + 1, j - 1) return Defining Arguments for Recursion In creating recursive methods, it is important to define the methods in ways that facilitate recursion. This sometimes requires we define additional paramaters that are passed to the method. For example, we defined the array reversal method as ReverseArray(A, i, j), not ReverseArray(A). Using Recursion 5 Using Recursion 6 Computing Powers The power function, p(n)=x n, can be defined recursively: p( n) = x p( n 1) if n = 0 This leads to an power function that runs in O(n) time (for we make n recursive s). We can do better than this, however. Recursive Squaring We can derive a more efficient linearly recursive algorithm by using repeated squaring: p( n) = x p( ( n 1) / 2) 2 p( n / 2) For example, 2 4 = 2 (4/2)2 = (2 4/2 ) 2 = (2 2 ) 2 = 4 2 = 16 2 5 = 2 1+(4/2)2 = 2(2 4/2 ) 2 = 2(2 2 ) 2 = 2(4 2 ) = 32 2 6 = 2 (6/ 2)2 = (2 6/2 ) 2 = (2 3 ) 2 = 8 2 = 64 2 7 = 2 1+(6/2)2 = 2(2 6/2 ) 2 = 2(2 3 ) 2 = 2(8 2 ) = 128. 2 if x = 0 if x > 0 is odd if x > 0 is even Using Recursion 7 Using Recursion 8

A Recursive Squaring Method Analyzing the Recursive Squaring Method Algorithm Power( n): Input: A number x and integer n = 0 Output: The value x n if n = 0 then return 1 if n is odd then y = Power( (n - 1)/ 2) return x y y y = Power( n/ 2) return y y Using Recursion 9 Algorithm Power( n): Input: A number x and integer n = 0 Output: The value x n if n = 0 then return 1 if n is odd then y = Power( (n - 1)/ 2) return x y y y = Power( n/ 2) return y y Each time we make a recursive we halve the value of n; hence, we make log n recursive s. That is, this method runs in O(log n) time. It is important that we used a variable twice here rather than ing the method twice. Using Recursion 10 Tail Recursion Tail recursion occurs when a linearly recursive method makes its recursive as its last step. The array reversal method is an example. Such methods can be easily converted to nonrecursive methods (which saves on some resources). Example: Algorithm IterativeReverseArray(A, i, j ): Input: An array A and nonnegative integer indices i and j Output: The reversal of the elements in A starting at index i and ending at j while i < j do Swap A[i ] and A[ j ] i = i + 1 j = j - 1 return Binary Recursion ( 4.1.2) Binary recursion occurs whenever there are two recursive s for each non-base case. Example: the DrawTicks method for drawing ticks on an English ruler. Using Recursion 11 Using Recursion 12

A Binary Recursive Method for Drawing Ticks // draw a tick with no label public static void drawonetick(int ticklength) { drawonetick(ticklength, -1); // draw one tick public static void drawonetick(int ticklength, int ticklabel) { for (int i = 0; i < ticklength; i++) System.out.print("-"); if (ticklabel >= 0) System.out.print(" " + ticklabel); System.out.print("\n"); public static void drawticks(int ticklength) { // draw ticks of given length if (ticklength > 0) { // stop when length drops to 0 drawticks(ticklength- 1); // recursively draw left ticks drawonetick(ticklength); // draw center tick drawticks(ticklength- 1); // recursively draw right ticks public static void drawruler(int ninches, int majorlength) { // draw ruler drawonetick(majorlength, 0); // draw tick 0 and its label for (int i = 1; i <= ninches; i++) { drawticks(majorlength- 1); // draw ticks for this inch drawonetick(majorlength, i); // draw tick i and its label Note the two recursive s Another Binary Recusive Method Problem: add all the numbers in an integer array A: Algorithm BinarySum(A, i, n): Input: An array A and integers i and n Output: The sum of the n integers in A starting at index i if n = 1 then return A[i ] return BinarySum(A, i, n/ 2) + BinarySum(A, i + n/ 2, n/ 2) Example trace: 0, 1 0, 2 1, 1 0, 4 2, 1 2, 2 3, 1 0, 8 4, 1 4, 2 5, 1 4, 4 6, 1 6, 2 7, 1 Using Recursion 13 Using Recursion 14 Computing Fibanacci Numbers Fibonacci numbers are defined recursively: F 0 = 0 F 1 = 1 F i = F i-1 + F i-2 for i > 1. As a recursive algorithm (first attempt): Algorithm BinaryFib(k): Input: Nonnegative integer k Output: The kth Fibonacci number F k return k return BinaryFib(k - 1) + BinaryFib(k - 2) Analyzing the Binary Recursion Fibonacci Algorithm Let n k denote number of recursive s made by BinaryFib(k). Then n 0 = 1 n 1 = 1 n 2 = n 1 + n 0 + 1 = 1 + 1 + 1 = 3 n 3 = n 2 + n 1 + 1 = 3 + 1 + 1 = 5 n 4 = n 3 + n 2 + 1 = 5 + 3 + 1 = 9 n 5 = n 4 + n 3 + 1 = 9 + 5 + 1 = 15 n 6 = n 5 + n 4 + 1 = 15 + 9 + 1 = 25 n 7 = n 6 + n 5 + 1 = 25 + 15 + 1 = 41 n 8 = n 7 + n 6 + 1 = 41 + 25 + 1 = 67. Note that the value at least doubles for every other value of n k. That is, n k > 2 k/2. It is exponential! Using Recursion 15 Using Recursion 16

A Better Fibonacci Algorithm Use linear recursion instead: Algorithm LinearFibonacci(k): Input: A nonnegative integer k Output: Pair of Fibonacci numbers (F k, F k-1 ) return (k, 0) (i, j) = LinearFibonacci(k -1) return (i +j, i) Runs in O(k) time. Multiple Recursion ( 4.1.3) Motivating example: summation puzzles pot + pan = bib dog + cat = pig boy + girl = baby Multiple recursion: makes potentially many recursive s (not just one or two). Using Recursion 17 Using Recursion 18 Algorithm for Multiple Recursion Visualizing PuzzleSolve Algorithm PuzzleSolve(k,S,U): Input: An integer k, sequence S, and set U (the universe of elements to test) Output: An enumeration of all k-length extensions to S using elements in U without repetitions for all e in U do Remove e from U {e is now being used Add e to the end of S Test whether S is a configuration that solves the puzzle if S solves the puzzle then return Solution found: S PuzzleSolve(k - 1, S,U) Add e back to U {e is now unused Remove e from the end of S Initial PuzzleSolve(3,(),{a,b,c) PuzzleSolve(2,a,{b,c) PuzzleSolve(2,b,{a,c) PuzzleSolve(2,c,{a,b) PuzzleSolve(1,ab,{c) PuzzleSolve(1,ba,{c) PuzzleSolve(1,ca,{b) abc bac cab PuzzleSolve(1,ac,{b) PuzzleSolve(1,bc,{a) PuzzleSolve(1,cb,{a) acb bca cba Using Recursion 19 Using Recursion 20