16RecursiveAlgorithms

16RecursiveAlgorithms - CMSC 132: Object-Oriented...

Info iconThis preview shows pages 1–8. Sign up to view the full content.

View Full Document Right Arrow Icon
CMSC 132: Object-Oriented Programming II Recursive Algorithms Department of Computer Science University of Maryland, College Park
Background image of page 1

Info iconThis preview has intentionally blurred sections. Sign up to view the full version.

View Full DocumentRight Arrow Icon
Recursion Recursion is a strategy for solving problems A procedure that calls itself Approach If ( problem instance is simple / trivial ) Solve it directly Else 1. Simplify problem instance into smaller instance(s) of the original problem 2. Solve smaller instance using same algorithm 3. Combine solution(s) to solve original problem
Background image of page 2
Recursive Algorithm Format 1. Base case Solve small problem directly 2. Recursive step Simplify problem into smaller subproblem(s) Recursively apply algorithm to subproblem(s) Calculate overall solution
Background image of page 3

Info iconThis preview has intentionally blurred sections. Sign up to view the full version.

View Full DocumentRight Arrow Icon
Example – Find To find an element in an array Base case If array is empty, return false Recursive step If 1 st element of array is given value, return true Skip 1 st element and recur on remainder of array
Background image of page 4
Example – Count To count # of elements in an array Base case If array is empty, return 0 Recursive step Skip 1 st element and recur on remainder of array Add 1 to result
Background image of page 5

Info iconThis preview has intentionally blurred sections. Sign up to view the full version.

View Full DocumentRight Arrow Icon
Auxiliary/Helper Functions Some recursive problems require an auxiliary function Auxiliary function – the one that actually is recursive Example: ArrayExamples.java
Background image of page 6
Example – Factorial Factorial definition n! = n n-1 n-2 n-3 3
Background image of page 7

Info iconThis preview has intentionally blurred sections. Sign up to view the full version.

View Full DocumentRight Arrow Icon
Image of page 8
This is the end of the preview. Sign up to access the rest of the document.

Page1 / 24

16RecursiveAlgorithms - CMSC 132: Object-Oriented...

This preview shows document pages 1 - 8. Sign up to view the full document.

View Full Document Right Arrow Icon
Ask a homework question - tutors are online