Recursion Vs Iterative
Recursion Vs Iterative
indirectly
Therearetwokeyrequirementstomakesurethattherecursionissuccessful:
Everyrecursivecallmustsimplifythecomputationinsomeway.
Theremustbespecialcasestohandlethesimplestcomputations.
IterationVs.Recursion
Ifarecursivemethodiscalledwithabasecase,themethodreturnsaresult.
Ifamethodiscalledwithamorecomplexproblem,themethoddividesthe
problemintotwoormoreconceptualpieces:apiecethatthemethodknows
howtodoandaslightlysmallerversionoftheoriginalproblem.Becausethis
newproblemlooksliketheoriginalproblem,themethodlaunchesarecursive
calltoworkonthesmallerproblem.
Forrecursiontoterminate,eachtimetherecursionmethodcallsitselfwitha
slightlysimplerversionoftheoriginalproblem,thesequenceofsmallerand
smallerproblemsmustconvergeonthebasecase.Whenthemethod
recognizesthebasecase,theresultisreturnedtothepreviousmethodcall
andasequenceofreturnsensuresallthewayupthelineuntiltheoriginal
callofthemethodeventuallyreturnsthefinalresult.
Bothiterationandrecursionarebasedonacontrolstructure:Iterationuses
arepetitionstructurerecursionusesaselectionstructure.
Bothiterationandrecursioninvolverepetition:Iterationexplicitlyusesa
repetitionstructurerecursionachievesrepetitionthroughrepeatedmethod
calls.
Iterationandrecursioneachinvolveaterminationtest:Iterationterminates
whentheloopcontinuationconditionfailsrecursionterminateswhenabase
caseisrecognized.
Iterationandrecursioncanoccurinfinitely:Aninfiniteloopoccurswith
iterationiftheloopcontinuationtestneverbecomesfalseinfiniterecursion
occursiftherecursionstepdoesnotreducetheprobleminamannerthat
convergesonthebasecase.
Recursionrepeatedlyinvokesthemechanism,andconsequentlythe
overhead,ofmethodcalls.Thiscanbeexpensiveinbothprocessortimeand
memoryspace.