SlideShare une entreprise Scribd logo
Recursion 1
Recursion
© 2013 Goodrich, Tamassia, Goldwasser
Recursion 2
The Recursion Pattern
 Recursion: when a method calls itself
 Classic example--the factorial function:
 n! = 1· 2· 3· ··· · (n-1)· n
 Recursive definition:
 As a Python method:







else
n
f
n
n
n
f
)
1
(
0
if
1
)
(
© 2013 Goodrich, Tamassia, Goldwasser
Recursion 3
Content of a Recursive Method
 Base case(s)
 Values of the input variables for which we perform
no recursive calls are called base cases (there
should be at least one base case).
 Every possible chain of recursive calls must
eventually reach a base case.
 Recursive calls
 Calls to the current method.
 Each recursive call should be defined so that it
makes progress towards a base case.
© 2013 Goodrich, Tamassia,
Goldwasser
Visualizing Recursion
 Recursion trace
 A box for each
recursive call
 An arrow from each
caller to callee
 An arrow from each
callee to caller
showing return value
 Example
Recursion 4
recursiveFactorial (4)
recursiveFactorial (3)
recursiveFactorial (2)
recursiveFactorial (1)
recursiveFactorial (0)
return 1
call
call
call
call
return 1*1 = 1
return 2*1 = 2
return 3*2 = 6
return 4*6 = 24 final answer
call
© 2013 Goodrich, Tamassia,
Goldwasser
Recursion 5
Example: English Ruler
 Print the ticks and numbers like an English ruler:
© 2013 Goodrich, Tamassia,
Goldwasser
6
Using Recursion
drawTicks(length)
Input: length of a ‘tick’
Output: ruler with tick of the given length in
the middle and smaller rulers on either side
Recursion
© 2013 Goodrich, Tamassia, Goldwasser
drawTicks(length)
if( length > 0 ) then
drawTicks( length  1 )
draw tick of the given length
drawTicks( length  1 )
Slide by Matt Stallmann
included with permission.
Recursion 7
Recursive Drawing Method
 The drawing method is
based on the following
recursive definition
 An interval with a
central tick length L >1
consists of:
 An interval with a central
tick length L1
 An single tick of length L
 An interval with a central
tick length L1
drawTicks (3) Output
drawTicks (0)
(previous pattern repeats )
drawOneTick (1)
drawTicks (1)
drawTicks (2)
drawOneTick (2)
drawTicks (2)
drawTicks (1)
drawTicks (0)
drawTicks (0)
drawTicks (0)
drawOneTick (1)
drawOneTick (3)
© 2013 Goodrich, Tamassia,
Goldwasser
Recursion 8
A Recursive Method for Drawing
Ticks on an English Ruler
Note the two
recursive calls
© 2013 Goodrich, Tamassia, Goldwasser
Binary Search
 Search for an integer, target, in an
ordered list.
© 2013 Goodrich, Tamassia, Goldwasser 9
Recursion
Visualizing Binary Search
 We consider three cases:
 If the target equals data[mid], then we have found the target.
 If target < data[mid], then we recur on the first half of the
sequence.
 If target > data[mid], then we recur on the second half of the
sequence.
© 2013 Goodrich, Tamassia, Goldwasser 10
Recursion
Analyzing Binary Search
 Runs in O(log n) time.
 The remaining portion of the list is of size
high – low + 1.
 After one comparison, this becomes one of
the following:
 Thus, each recursive call divides the search
region in half; hence, there can be at most
log n levels.
© 2013 Goodrich, Tamassia, Goldwasser 11
Recursion
Recursion 12
Linear Recursion
 Test for base cases
 Begin by testing for a set of base cases (there should be
at least one).
 Every possible chain of recursive calls must eventually
reach a base case, and the handling of each base case
should not use recursion.
 Recur once
 Perform a single recursive call
 This step may have a test that decides which of several
possible recursive calls to make, but it should ultimately
make just one of these calls
 Define each possible recursive call so that it makes
progress towards a base case.
© 2013 Goodrich, Tamassia, Goldwasser
Recursion 13
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]
else
return LinearSum(A, n - 1) +
A[n - 1]
Example recursion trace:
LinearSum(A,5)
LinearSum(A,1)
LinearSum(A,2)
LinearSum(A,3)
LinearSum(A,4)
call
call
call
call return A[0] = 4
return 4 + A[1] = 4 + 3 = 7
return 7 + A[2] = 7 + 6 = 13
return 13 + A[3] = 13 + 2 = 15
call return 15 + A[4] = 15 + 5 = 20
© 2013 Goodrich, Tamassia, Goldwasser
Recursion 14
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
© 2013 Goodrich, Tamassia, Goldwasser
Recursion 15
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).
 Python version:
© 2013 Goodrich, Tamassia, Goldwasser
Recursion 16
Computing Powers
 The power function, p(x,n)=xn, can be
defined recursively:
 This leads to an power function that runs in
O(n) time (for we make n recursive calls).
 We can do better than this, however.
î
í
ì
-
×
=
=
else
)
1
,
(
0
if
1
)
,
(
n
x
p
x
n
n
x
p
© 2013 Goodrich, Tamassia, Goldwasser
Recursion 17
Recursive Squaring
 We can derive a more efficient linearly
recursive algorithm by using repeated squaring:
 For example,
24 = 2(4/2)2 = (24/2)2 = (22)2 = 42 = 16
25 = 21+(4/2)2 = 2(24/2)2 = 2(22)2 = 2(42) = 32
26 = 2(6/ 2)2 = (26/2)2 = (23)2 = 82 = 64
27 = 21+(6/2)2 = 2(26/2)2 = 2(23)2 = 2(82) = 128.
© 2013 Goodrich, Tamassia, Goldwasser
Recursion 18
Recursive Squaring Method
Algorithm Power(x, n):
Input: A number x and integer n = 0
Output: The value xn
if n = 0 then
return 1
if n is odd then
y = Power(x, (n - 1)/ 2)
return x · y ·y
else
y = Power(x, n/ 2)
return y · y
© 2013 Goodrich, Tamassia, Goldwasser
Recursion 19
Analysis
Algorithm Power(x, n):
Input: A number x and
integer n = 0
Output: The value xn
if n = 0 then
return 1
if n is odd then
y = Power(x, (n - 1)/ 2)
return x · y · y
else
y = Power(x, n/ 2)
return y · y
It is important that we
use a variable twice
here rather than calling
the method twice.
Each time we make a
recursive call we halve
the value of n; hence,
we make log n recursive
calls. That is, this
method runs in O(log n)
time.
© 2013 Goodrich, Tamassia, Goldwasser
Recursion 20
Tail Recursion
 Tail recursion occurs when a linearly recursive
method makes its recursive call as its last step.
 The array reversal method is an example.
 Such methods can be easily converted to non-
recursive 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
© 2013 Goodrich, Tamassia, Goldwasser
Recursion 21
Binary Recursion
 Binary recursion occurs whenever there are two
recursive calls for each non-base case.
 Example from before: the DrawTicks method for
drawing ticks on an English ruler.
© 2013 Goodrich, Tamassia, Goldwasser
Recursion 22
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:
3, 1
2, 2
0, 4
2, 1
1, 1
0, 1
0, 8
0, 2
7, 1
6, 2
4, 4
6, 1
5, 1
4, 2
4, 1
© 2013 Goodrich, Tamassia, Goldwasser
Recursion 23
Computing Fibonacci Numbers
 Fibonacci numbers are defined recursively:
F0 = 0
F1 = 1
Fi = Fi-1
+ Fi-2 for i > 1.
 Recursive algorithm (first attempt):
Algorithm BinaryFib(k):
Input: Nonnegative integer k
Output: The kth Fibonacci number Fk
if k = 1 then
return k
else
return BinaryFib(k - 1) + BinaryFib(k - 2)
© 2013 Goodrich, Tamassia, Goldwasser
Recursion 24
Analysis
 Let nk be the number of recursive calls by BinaryFib(k)
 n0 = 1
 n1 = 1
 n2 = n1 + n0 + 1 = 1 + 1 + 1 = 3
 n3 = n2 + n1 + 1 = 3 + 1 + 1 = 5
 n4 = n3 + n2 + 1 = 5 + 3 + 1 = 9
 n5 = n4 + n3 + 1 = 9 + 5 + 1 = 15
 n6 = n5 + n4 + 1 = 15 + 9 + 1 = 25
 n7 = n6 + n5 + 1 = 25 + 15 + 1 = 41
 n8 = n7 + n6 + 1 = 41 + 25 + 1 = 67.
 Note that nk at least doubles every other time
 That is, nk > 2k/2. It is exponential!
© 2013 Goodrich, Tamassia, Goldwasser
© 2013 Goodrich, Tamassia, Goldwasser 25
Recursion
Recursion 26
A Better Fibonacci Algorithm
 Use linear recursion instead
Algorithm LinearFibonacci(k):
Input: A nonnegative integer k
Output: Pair of Fibonacci numbers (Fk , Fk1)
if k = 1 then
return (k, 0)
else
(i, j) = LinearFibonacci(k  1)
return (i +j, i)
 LinearFibonacci makes k1 recursive calls
© 2013 Goodrich, Tamassia, Goldwasser

Contenu connexe

Similaire à Ch4-recursion.ppt

Fast Identification of Heavy Hitters by Cached and Packed Group Testing
Fast Identification of Heavy Hitters by Cached and Packed Group TestingFast Identification of Heavy Hitters by Cached and Packed Group Testing
Fast Identification of Heavy Hitters by Cached and Packed Group Testing
Rakuten Group, Inc.
 
Data Structures- Part5 recursion
Data Structures- Part5 recursionData Structures- Part5 recursion
Data Structures- Part5 recursion
Abdullah Al-hazmy
 
dynamic-programming
dynamic-programmingdynamic-programming
dynamic-programming
MuhammadSheraz836877
 
Unit-3 greedy method, Prim's algorithm, Kruskal's algorithm.pdf
Unit-3 greedy method, Prim's algorithm, Kruskal's algorithm.pdfUnit-3 greedy method, Prim's algorithm, Kruskal's algorithm.pdf
Unit-3 greedy method, Prim's algorithm, Kruskal's algorithm.pdf
yashodamb
 
Answers withexplanations
Answers withexplanationsAnswers withexplanations
Answers withexplanations
Gopi Saiteja
 
dynamic programming Rod cutting class
dynamic programming Rod cutting classdynamic programming Rod cutting class
dynamic programming Rod cutting class
giridaroori
 
Analysis of Algorithum
Analysis of AlgorithumAnalysis of Algorithum
Analysis of Algorithum
Ain-ul-Moiz Khawaja
 
Daa notes 2
Daa notes 2Daa notes 2
Daa notes 2
smruti sarangi
 
Time-Series Analysis on Multiperiodic Conditional Correlation by Sparse Covar...
Time-Series Analysis on Multiperiodic Conditional Correlation by Sparse Covar...Time-Series Analysis on Multiperiodic Conditional Correlation by Sparse Covar...
Time-Series Analysis on Multiperiodic Conditional Correlation by Sparse Covar...
Michael Lie
 
module1_Introductiontoalgorithms_2022.pdf
module1_Introductiontoalgorithms_2022.pdfmodule1_Introductiontoalgorithms_2022.pdf
module1_Introductiontoalgorithms_2022.pdf
Shiwani Gupta
 
parameterized complexity for graph Motif
parameterized complexity for graph Motifparameterized complexity for graph Motif
parameterized complexity for graph Motif
AMR koura
 
DS Unit-1.pptx very easy to understand..
DS Unit-1.pptx very easy to understand..DS Unit-1.pptx very easy to understand..
DS Unit-1.pptx very easy to understand..
KarthikeyaLanka1
 
Subquad multi ff
Subquad multi ffSubquad multi ff
Subquad multi ff
Fabian Velazquez
 
Talk iccf 19_ben_hammouda
Talk iccf 19_ben_hammoudaTalk iccf 19_ben_hammouda
Talk iccf 19_ben_hammouda
Chiheb Ben Hammouda
 
NPTEL QUIZ.docx
NPTEL QUIZ.docxNPTEL QUIZ.docx
NPTEL QUIZ.docx
GEETHAR59
 
DAA - UNIT 4 - Engineering.pptx
DAA - UNIT 4 - Engineering.pptxDAA - UNIT 4 - Engineering.pptx
DAA - UNIT 4 - Engineering.pptx
vaishnavi339314
 
Explanation on Tensorflow example -Deep mnist for expert
Explanation on Tensorflow example -Deep mnist for expertExplanation on Tensorflow example -Deep mnist for expert
Explanation on Tensorflow example -Deep mnist for expert
홍배 김
 
Design and Analysis of Algorithms Lecture Notes
Design and Analysis of Algorithms Lecture NotesDesign and Analysis of Algorithms Lecture Notes
Design and Analysis of Algorithms Lecture Notes
Sreedhar Chowdam
 
Lec7
Lec7Lec7

Similaire à Ch4-recursion.ppt (20)

Fast Identification of Heavy Hitters by Cached and Packed Group Testing
Fast Identification of Heavy Hitters by Cached and Packed Group TestingFast Identification of Heavy Hitters by Cached and Packed Group Testing
Fast Identification of Heavy Hitters by Cached and Packed Group Testing
 
Data Structures- Part5 recursion
Data Structures- Part5 recursionData Structures- Part5 recursion
Data Structures- Part5 recursion
 
dynamic-programming
dynamic-programmingdynamic-programming
dynamic-programming
 
Unit-3 greedy method, Prim's algorithm, Kruskal's algorithm.pdf
Unit-3 greedy method, Prim's algorithm, Kruskal's algorithm.pdfUnit-3 greedy method, Prim's algorithm, Kruskal's algorithm.pdf
Unit-3 greedy method, Prim's algorithm, Kruskal's algorithm.pdf
 
Answers withexplanations
Answers withexplanationsAnswers withexplanations
Answers withexplanations
 
dynamic programming Rod cutting class
dynamic programming Rod cutting classdynamic programming Rod cutting class
dynamic programming Rod cutting class
 
Analysis of Algorithum
Analysis of AlgorithumAnalysis of Algorithum
Analysis of Algorithum
 
Daa notes 2
Daa notes 2Daa notes 2
Daa notes 2
 
Time-Series Analysis on Multiperiodic Conditional Correlation by Sparse Covar...
Time-Series Analysis on Multiperiodic Conditional Correlation by Sparse Covar...Time-Series Analysis on Multiperiodic Conditional Correlation by Sparse Covar...
Time-Series Analysis on Multiperiodic Conditional Correlation by Sparse Covar...
 
module1_Introductiontoalgorithms_2022.pdf
module1_Introductiontoalgorithms_2022.pdfmodule1_Introductiontoalgorithms_2022.pdf
module1_Introductiontoalgorithms_2022.pdf
 
parameterized complexity for graph Motif
parameterized complexity for graph Motifparameterized complexity for graph Motif
parameterized complexity for graph Motif
 
DS Unit-1.pptx very easy to understand..
DS Unit-1.pptx very easy to understand..DS Unit-1.pptx very easy to understand..
DS Unit-1.pptx very easy to understand..
 
Subquad multi ff
Subquad multi ffSubquad multi ff
Subquad multi ff
 
Talk iccf 19_ben_hammouda
Talk iccf 19_ben_hammoudaTalk iccf 19_ben_hammouda
Talk iccf 19_ben_hammouda
 
NPTEL QUIZ.docx
NPTEL QUIZ.docxNPTEL QUIZ.docx
NPTEL QUIZ.docx
 
DAA - UNIT 4 - Engineering.pptx
DAA - UNIT 4 - Engineering.pptxDAA - UNIT 4 - Engineering.pptx
DAA - UNIT 4 - Engineering.pptx
 
Explanation on Tensorflow example -Deep mnist for expert
Explanation on Tensorflow example -Deep mnist for expertExplanation on Tensorflow example -Deep mnist for expert
Explanation on Tensorflow example -Deep mnist for expert
 
R Language Introduction
R Language IntroductionR Language Introduction
R Language Introduction
 
Design and Analysis of Algorithms Lecture Notes
Design and Analysis of Algorithms Lecture NotesDesign and Analysis of Algorithms Lecture Notes
Design and Analysis of Algorithms Lecture Notes
 
Lec7
Lec7Lec7
Lec7
 

Dernier

Levelwise PageRank with Loop-Based Dead End Handling Strategy : SHORT REPORT ...
Levelwise PageRank with Loop-Based Dead End Handling Strategy : SHORT REPORT ...Levelwise PageRank with Loop-Based Dead End Handling Strategy : SHORT REPORT ...
Levelwise PageRank with Loop-Based Dead End Handling Strategy : SHORT REPORT ...
Subhajit Sahu
 
【社内勉強会資料_Octo: An Open-Source Generalist Robot Policy】
【社内勉強会資料_Octo: An Open-Source Generalist Robot Policy】【社内勉強会資料_Octo: An Open-Source Generalist Robot Policy】
【社内勉強会資料_Octo: An Open-Source Generalist Robot Policy】
NABLAS株式会社
 
FP Growth Algorithm and its Applications
FP Growth Algorithm and its ApplicationsFP Growth Algorithm and its Applications
FP Growth Algorithm and its Applications
MaleehaSheikh2
 
一比一原版(UIUC毕业证)伊利诺伊大学|厄巴纳-香槟分校毕业证如何办理
一比一原版(UIUC毕业证)伊利诺伊大学|厄巴纳-香槟分校毕业证如何办理一比一原版(UIUC毕业证)伊利诺伊大学|厄巴纳-香槟分校毕业证如何办理
一比一原版(UIUC毕业证)伊利诺伊大学|厄巴纳-香槟分校毕业证如何办理
ahzuo
 
Adjusting primitives for graph : SHORT REPORT / NOTES
Adjusting primitives for graph : SHORT REPORT / NOTESAdjusting primitives for graph : SHORT REPORT / NOTES
Adjusting primitives for graph : SHORT REPORT / NOTES
Subhajit Sahu
 
一比一原版(BU毕业证)波士顿大学毕业证成绩单
一比一原版(BU毕业证)波士顿大学毕业证成绩单一比一原版(BU毕业证)波士顿大学毕业证成绩单
一比一原版(BU毕业证)波士顿大学毕业证成绩单
ewymefz
 
一比一原版(CBU毕业证)卡普顿大学毕业证成绩单
一比一原版(CBU毕业证)卡普顿大学毕业证成绩单一比一原版(CBU毕业证)卡普顿大学毕业证成绩单
一比一原版(CBU毕业证)卡普顿大学毕业证成绩单
nscud
 
一比一原版(QU毕业证)皇后大学毕业证成绩单
一比一原版(QU毕业证)皇后大学毕业证成绩单一比一原版(QU毕业证)皇后大学毕业证成绩单
一比一原版(QU毕业证)皇后大学毕业证成绩单
enxupq
 
一比一原版(CU毕业证)卡尔顿大学毕业证成绩单
一比一原版(CU毕业证)卡尔顿大学毕业证成绩单一比一原版(CU毕业证)卡尔顿大学毕业证成绩单
一比一原版(CU毕业证)卡尔顿大学毕业证成绩单
yhkoc
 
Criminal IP - Threat Hunting Webinar.pdf
Criminal IP - Threat Hunting Webinar.pdfCriminal IP - Threat Hunting Webinar.pdf
Criminal IP - Threat Hunting Webinar.pdf
Criminal IP
 
Empowering Data Analytics Ecosystem.pptx
Empowering Data Analytics Ecosystem.pptxEmpowering Data Analytics Ecosystem.pptx
Empowering Data Analytics Ecosystem.pptx
benishzehra469
 
Best best suvichar in gujarati english meaning of this sentence as Silk road ...
Best best suvichar in gujarati english meaning of this sentence as Silk road ...Best best suvichar in gujarati english meaning of this sentence as Silk road ...
Best best suvichar in gujarati english meaning of this sentence as Silk road ...
AbhimanyuSinha9
 
一比一原版(UofM毕业证)明尼苏达大学毕业证成绩单
一比一原版(UofM毕业证)明尼苏达大学毕业证成绩单一比一原版(UofM毕业证)明尼苏达大学毕业证成绩单
一比一原版(UofM毕业证)明尼苏达大学毕业证成绩单
ewymefz
 
Opendatabay - Open Data Marketplace.pptx
Opendatabay - Open Data Marketplace.pptxOpendatabay - Open Data Marketplace.pptx
Opendatabay - Open Data Marketplace.pptx
Opendatabay
 
一比一原版(RUG毕业证)格罗宁根大学毕业证成绩单
一比一原版(RUG毕业证)格罗宁根大学毕业证成绩单一比一原版(RUG毕业证)格罗宁根大学毕业证成绩单
一比一原版(RUG毕业证)格罗宁根大学毕业证成绩单
vcaxypu
 
一比一原版(CBU毕业证)不列颠海角大学毕业证成绩单
一比一原版(CBU毕业证)不列颠海角大学毕业证成绩单一比一原版(CBU毕业证)不列颠海角大学毕业证成绩单
一比一原版(CBU毕业证)不列颠海角大学毕业证成绩单
nscud
 
The affect of service quality and online reviews on customer loyalty in the E...
The affect of service quality and online reviews on customer loyalty in the E...The affect of service quality and online reviews on customer loyalty in the E...
The affect of service quality and online reviews on customer loyalty in the E...
jerlynmaetalle
 
一比一原版(UniSA毕业证书)南澳大学毕业证如何办理
一比一原版(UniSA毕业证书)南澳大学毕业证如何办理一比一原版(UniSA毕业证书)南澳大学毕业证如何办理
一比一原版(UniSA毕业证书)南澳大学毕业证如何办理
slg6lamcq
 
哪里卖(usq毕业证书)南昆士兰大学毕业证研究生文凭证书托福证书原版一模一样
哪里卖(usq毕业证书)南昆士兰大学毕业证研究生文凭证书托福证书原版一模一样哪里卖(usq毕业证书)南昆士兰大学毕业证研究生文凭证书托福证书原版一模一样
哪里卖(usq毕业证书)南昆士兰大学毕业证研究生文凭证书托福证书原版一模一样
axoqas
 
一比一原版(CBU毕业证)卡普顿大学毕业证如何办理
一比一原版(CBU毕业证)卡普顿大学毕业证如何办理一比一原版(CBU毕业证)卡普顿大学毕业证如何办理
一比一原版(CBU毕业证)卡普顿大学毕业证如何办理
ahzuo
 

Dernier (20)

Levelwise PageRank with Loop-Based Dead End Handling Strategy : SHORT REPORT ...
Levelwise PageRank with Loop-Based Dead End Handling Strategy : SHORT REPORT ...Levelwise PageRank with Loop-Based Dead End Handling Strategy : SHORT REPORT ...
Levelwise PageRank with Loop-Based Dead End Handling Strategy : SHORT REPORT ...
 
【社内勉強会資料_Octo: An Open-Source Generalist Robot Policy】
【社内勉強会資料_Octo: An Open-Source Generalist Robot Policy】【社内勉強会資料_Octo: An Open-Source Generalist Robot Policy】
【社内勉強会資料_Octo: An Open-Source Generalist Robot Policy】
 
FP Growth Algorithm and its Applications
FP Growth Algorithm and its ApplicationsFP Growth Algorithm and its Applications
FP Growth Algorithm and its Applications
 
一比一原版(UIUC毕业证)伊利诺伊大学|厄巴纳-香槟分校毕业证如何办理
一比一原版(UIUC毕业证)伊利诺伊大学|厄巴纳-香槟分校毕业证如何办理一比一原版(UIUC毕业证)伊利诺伊大学|厄巴纳-香槟分校毕业证如何办理
一比一原版(UIUC毕业证)伊利诺伊大学|厄巴纳-香槟分校毕业证如何办理
 
Adjusting primitives for graph : SHORT REPORT / NOTES
Adjusting primitives for graph : SHORT REPORT / NOTESAdjusting primitives for graph : SHORT REPORT / NOTES
Adjusting primitives for graph : SHORT REPORT / NOTES
 
一比一原版(BU毕业证)波士顿大学毕业证成绩单
一比一原版(BU毕业证)波士顿大学毕业证成绩单一比一原版(BU毕业证)波士顿大学毕业证成绩单
一比一原版(BU毕业证)波士顿大学毕业证成绩单
 
一比一原版(CBU毕业证)卡普顿大学毕业证成绩单
一比一原版(CBU毕业证)卡普顿大学毕业证成绩单一比一原版(CBU毕业证)卡普顿大学毕业证成绩单
一比一原版(CBU毕业证)卡普顿大学毕业证成绩单
 
一比一原版(QU毕业证)皇后大学毕业证成绩单
一比一原版(QU毕业证)皇后大学毕业证成绩单一比一原版(QU毕业证)皇后大学毕业证成绩单
一比一原版(QU毕业证)皇后大学毕业证成绩单
 
一比一原版(CU毕业证)卡尔顿大学毕业证成绩单
一比一原版(CU毕业证)卡尔顿大学毕业证成绩单一比一原版(CU毕业证)卡尔顿大学毕业证成绩单
一比一原版(CU毕业证)卡尔顿大学毕业证成绩单
 
Criminal IP - Threat Hunting Webinar.pdf
Criminal IP - Threat Hunting Webinar.pdfCriminal IP - Threat Hunting Webinar.pdf
Criminal IP - Threat Hunting Webinar.pdf
 
Empowering Data Analytics Ecosystem.pptx
Empowering Data Analytics Ecosystem.pptxEmpowering Data Analytics Ecosystem.pptx
Empowering Data Analytics Ecosystem.pptx
 
Best best suvichar in gujarati english meaning of this sentence as Silk road ...
Best best suvichar in gujarati english meaning of this sentence as Silk road ...Best best suvichar in gujarati english meaning of this sentence as Silk road ...
Best best suvichar in gujarati english meaning of this sentence as Silk road ...
 
一比一原版(UofM毕业证)明尼苏达大学毕业证成绩单
一比一原版(UofM毕业证)明尼苏达大学毕业证成绩单一比一原版(UofM毕业证)明尼苏达大学毕业证成绩单
一比一原版(UofM毕业证)明尼苏达大学毕业证成绩单
 
Opendatabay - Open Data Marketplace.pptx
Opendatabay - Open Data Marketplace.pptxOpendatabay - Open Data Marketplace.pptx
Opendatabay - Open Data Marketplace.pptx
 
一比一原版(RUG毕业证)格罗宁根大学毕业证成绩单
一比一原版(RUG毕业证)格罗宁根大学毕业证成绩单一比一原版(RUG毕业证)格罗宁根大学毕业证成绩单
一比一原版(RUG毕业证)格罗宁根大学毕业证成绩单
 
一比一原版(CBU毕业证)不列颠海角大学毕业证成绩单
一比一原版(CBU毕业证)不列颠海角大学毕业证成绩单一比一原版(CBU毕业证)不列颠海角大学毕业证成绩单
一比一原版(CBU毕业证)不列颠海角大学毕业证成绩单
 
The affect of service quality and online reviews on customer loyalty in the E...
The affect of service quality and online reviews on customer loyalty in the E...The affect of service quality and online reviews on customer loyalty in the E...
The affect of service quality and online reviews on customer loyalty in the E...
 
一比一原版(UniSA毕业证书)南澳大学毕业证如何办理
一比一原版(UniSA毕业证书)南澳大学毕业证如何办理一比一原版(UniSA毕业证书)南澳大学毕业证如何办理
一比一原版(UniSA毕业证书)南澳大学毕业证如何办理
 
哪里卖(usq毕业证书)南昆士兰大学毕业证研究生文凭证书托福证书原版一模一样
哪里卖(usq毕业证书)南昆士兰大学毕业证研究生文凭证书托福证书原版一模一样哪里卖(usq毕业证书)南昆士兰大学毕业证研究生文凭证书托福证书原版一模一样
哪里卖(usq毕业证书)南昆士兰大学毕业证研究生文凭证书托福证书原版一模一样
 
一比一原版(CBU毕业证)卡普顿大学毕业证如何办理
一比一原版(CBU毕业证)卡普顿大学毕业证如何办理一比一原版(CBU毕业证)卡普顿大学毕业证如何办理
一比一原版(CBU毕业证)卡普顿大学毕业证如何办理
 

Ch4-recursion.ppt

  • 1. Recursion 1 Recursion © 2013 Goodrich, Tamassia, Goldwasser
  • 2. Recursion 2 The Recursion Pattern  Recursion: when a method calls itself  Classic example--the factorial function:  n! = 1· 2· 3· ··· · (n-1)· n  Recursive definition:  As a Python method:        else n f n n n f ) 1 ( 0 if 1 ) ( © 2013 Goodrich, Tamassia, Goldwasser
  • 3. Recursion 3 Content of a Recursive Method  Base case(s)  Values of the input variables for which we perform no recursive calls are called base cases (there should be at least one base case).  Every possible chain of recursive calls must eventually reach a base case.  Recursive calls  Calls to the current method.  Each recursive call should be defined so that it makes progress towards a base case. © 2013 Goodrich, Tamassia, Goldwasser
  • 4. Visualizing Recursion  Recursion trace  A box for each recursive call  An arrow from each caller to callee  An arrow from each callee to caller showing return value  Example Recursion 4 recursiveFactorial (4) recursiveFactorial (3) recursiveFactorial (2) recursiveFactorial (1) recursiveFactorial (0) return 1 call call call call return 1*1 = 1 return 2*1 = 2 return 3*2 = 6 return 4*6 = 24 final answer call © 2013 Goodrich, Tamassia, Goldwasser
  • 5. Recursion 5 Example: English Ruler  Print the ticks and numbers like an English ruler: © 2013 Goodrich, Tamassia, Goldwasser
  • 6. 6 Using Recursion drawTicks(length) Input: length of a ‘tick’ Output: ruler with tick of the given length in the middle and smaller rulers on either side Recursion © 2013 Goodrich, Tamassia, Goldwasser drawTicks(length) if( length > 0 ) then drawTicks( length  1 ) draw tick of the given length drawTicks( length  1 ) Slide by Matt Stallmann included with permission.
  • 7. Recursion 7 Recursive Drawing Method  The drawing method is based on the following recursive definition  An interval with a central tick length L >1 consists of:  An interval with a central tick length L1  An single tick of length L  An interval with a central tick length L1 drawTicks (3) Output drawTicks (0) (previous pattern repeats ) drawOneTick (1) drawTicks (1) drawTicks (2) drawOneTick (2) drawTicks (2) drawTicks (1) drawTicks (0) drawTicks (0) drawTicks (0) drawOneTick (1) drawOneTick (3) © 2013 Goodrich, Tamassia, Goldwasser
  • 8. Recursion 8 A Recursive Method for Drawing Ticks on an English Ruler Note the two recursive calls © 2013 Goodrich, Tamassia, Goldwasser
  • 9. Binary Search  Search for an integer, target, in an ordered list. © 2013 Goodrich, Tamassia, Goldwasser 9 Recursion
  • 10. Visualizing Binary Search  We consider three cases:  If the target equals data[mid], then we have found the target.  If target < data[mid], then we recur on the first half of the sequence.  If target > data[mid], then we recur on the second half of the sequence. © 2013 Goodrich, Tamassia, Goldwasser 10 Recursion
  • 11. Analyzing Binary Search  Runs in O(log n) time.  The remaining portion of the list is of size high – low + 1.  After one comparison, this becomes one of the following:  Thus, each recursive call divides the search region in half; hence, there can be at most log n levels. © 2013 Goodrich, Tamassia, Goldwasser 11 Recursion
  • 12. Recursion 12 Linear Recursion  Test for base cases  Begin by testing for a set of base cases (there should be at least one).  Every possible chain of recursive calls must eventually reach a base case, and the handling of each base case should not use recursion.  Recur once  Perform a single recursive call  This step may have a test that decides which of several possible recursive calls to make, but it should ultimately make just one of these calls  Define each possible recursive call so that it makes progress towards a base case. © 2013 Goodrich, Tamassia, Goldwasser
  • 13. Recursion 13 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] else return LinearSum(A, n - 1) + A[n - 1] Example recursion trace: LinearSum(A,5) LinearSum(A,1) LinearSum(A,2) LinearSum(A,3) LinearSum(A,4) call call call call return A[0] = 4 return 4 + A[1] = 4 + 3 = 7 return 7 + A[2] = 7 + 6 = 13 return 13 + A[3] = 13 + 2 = 15 call return 15 + A[4] = 15 + 5 = 20 © 2013 Goodrich, Tamassia, Goldwasser
  • 14. Recursion 14 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 © 2013 Goodrich, Tamassia, Goldwasser
  • 15. Recursion 15 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).  Python version: © 2013 Goodrich, Tamassia, Goldwasser
  • 16. Recursion 16 Computing Powers  The power function, p(x,n)=xn, can be defined recursively:  This leads to an power function that runs in O(n) time (for we make n recursive calls).  We can do better than this, however. î í ì - × = = else ) 1 , ( 0 if 1 ) , ( n x p x n n x p © 2013 Goodrich, Tamassia, Goldwasser
  • 17. Recursion 17 Recursive Squaring  We can derive a more efficient linearly recursive algorithm by using repeated squaring:  For example, 24 = 2(4/2)2 = (24/2)2 = (22)2 = 42 = 16 25 = 21+(4/2)2 = 2(24/2)2 = 2(22)2 = 2(42) = 32 26 = 2(6/ 2)2 = (26/2)2 = (23)2 = 82 = 64 27 = 21+(6/2)2 = 2(26/2)2 = 2(23)2 = 2(82) = 128. © 2013 Goodrich, Tamassia, Goldwasser
  • 18. Recursion 18 Recursive Squaring Method Algorithm Power(x, n): Input: A number x and integer n = 0 Output: The value xn if n = 0 then return 1 if n is odd then y = Power(x, (n - 1)/ 2) return x · y ·y else y = Power(x, n/ 2) return y · y © 2013 Goodrich, Tamassia, Goldwasser
  • 19. Recursion 19 Analysis Algorithm Power(x, n): Input: A number x and integer n = 0 Output: The value xn if n = 0 then return 1 if n is odd then y = Power(x, (n - 1)/ 2) return x · y · y else y = Power(x, n/ 2) return y · y It is important that we use a variable twice here rather than calling the method twice. Each time we make a recursive call we halve the value of n; hence, we make log n recursive calls. That is, this method runs in O(log n) time. © 2013 Goodrich, Tamassia, Goldwasser
  • 20. Recursion 20 Tail Recursion  Tail recursion occurs when a linearly recursive method makes its recursive call as its last step.  The array reversal method is an example.  Such methods can be easily converted to non- recursive 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 © 2013 Goodrich, Tamassia, Goldwasser
  • 21. Recursion 21 Binary Recursion  Binary recursion occurs whenever there are two recursive calls for each non-base case.  Example from before: the DrawTicks method for drawing ticks on an English ruler. © 2013 Goodrich, Tamassia, Goldwasser
  • 22. Recursion 22 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: 3, 1 2, 2 0, 4 2, 1 1, 1 0, 1 0, 8 0, 2 7, 1 6, 2 4, 4 6, 1 5, 1 4, 2 4, 1 © 2013 Goodrich, Tamassia, Goldwasser
  • 23. Recursion 23 Computing Fibonacci Numbers  Fibonacci numbers are defined recursively: F0 = 0 F1 = 1 Fi = Fi-1 + Fi-2 for i > 1.  Recursive algorithm (first attempt): Algorithm BinaryFib(k): Input: Nonnegative integer k Output: The kth Fibonacci number Fk if k = 1 then return k else return BinaryFib(k - 1) + BinaryFib(k - 2) © 2013 Goodrich, Tamassia, Goldwasser
  • 24. Recursion 24 Analysis  Let nk be the number of recursive calls by BinaryFib(k)  n0 = 1  n1 = 1  n2 = n1 + n0 + 1 = 1 + 1 + 1 = 3  n3 = n2 + n1 + 1 = 3 + 1 + 1 = 5  n4 = n3 + n2 + 1 = 5 + 3 + 1 = 9  n5 = n4 + n3 + 1 = 9 + 5 + 1 = 15  n6 = n5 + n4 + 1 = 15 + 9 + 1 = 25  n7 = n6 + n5 + 1 = 25 + 15 + 1 = 41  n8 = n7 + n6 + 1 = 41 + 25 + 1 = 67.  Note that nk at least doubles every other time  That is, nk > 2k/2. It is exponential! © 2013 Goodrich, Tamassia, Goldwasser
  • 25. © 2013 Goodrich, Tamassia, Goldwasser 25 Recursion
  • 26. Recursion 26 A Better Fibonacci Algorithm  Use linear recursion instead Algorithm LinearFibonacci(k): Input: A nonnegative integer k Output: Pair of Fibonacci numbers (Fk , Fk1) if k = 1 then return (k, 0) else (i, j) = LinearFibonacci(k  1) return (i +j, i)  LinearFibonacci makes k1 recursive calls © 2013 Goodrich, Tamassia, Goldwasser