Week 06 Recursion
Week 06 Recursion
RECURSION
Truong Thi Ngoc Phuong
Contents
2
Introduction
Triangular Numbers
Factorials
A Recursive Binary Search
The Towers of Hanoi
Mergesort
3 Introduction
4 Triangular Numbers: Examples
5 Finding nth Term using a Loop
6
Finding nth Term using Recursion
7
It calls itself
When it calls itself, it does so to solve a smaller
problem
There is some version of the problem that is simple
enough that the routine can solve it, and return, without
calling itself
Is recursion efficient?
No
Address of calling methods must be remembered (in stack)
Intermediate arguments must also be stored
Factorials
11
Factorials
12
Loop
13 Binary Search: Recursion vs. Loop
Recursion
14 Binary Search: Recursion vs. Loop
Divide-and-conquer
15
Number of Copies
Copied to Workspace
Copied back to
original array
NEX
T
29 Eliminate recursion
Recursion: inefficient
30