SavCpp8PowerPointsSavitch_ch_14_第1页
SavCpp8PowerPointsSavitch_ch_14_第2页
SavCpp8PowerPointsSavitch_ch_14_第3页
SavCpp8PowerPointsSavitch_ch_14_第4页
SavCpp8PowerPointsSavitch_ch_14_第5页
已阅读5页,还剩65页未读 继续免费阅读

下载本文档

版权说明:本文档由用户提供并上传,收益归属内容提供方,若内容存在侵权,请进行举报或认领

文档简介

Chapter14,Recursion,Overview,14.1RecursiveFunctionsforTasks14.2RecursiveFunctionsforValues14.3ThinkingRecursively,Slide14-3,14.1,RecursiveFunctionsforTasks,RecursiveFunctionsforTasks,ArecursivefunctioncontainsacalltoitselfWhenbreakingataskintosubtasks,itmaybethatthesubtaskisasmallerexampleofthesametaskSearchinganarraycouldbedividedintosearchingthefirstandsecondhalvesofthearraySearchingeachhalfisasmallerversionofsearchingthewholearrayTaskslikethiscanbesolvedwithrecursivefunctions,Slide14-5,CaseStudy:VerticalNumbers,ProblemDefinition:voidwrite_vertical(intn);/Precondition:n=0/Postcondition:niswrittentothescreenvertically/witheachdigitonaseparateline,Slide14-6,CaseStudy:VerticalNumbers,Algorithmdesign:Simplestcase:Ifnisonedigitlong,writethenumberTypicalcase:1)Outputallbutthelastdigitvertically2)WritethelastdigitStep1isasmallerversionoftheoriginaltaskStep2isthesimplestcase,Slide14-7,CaseStudy:VerticalNumbers(cont.),Thewrite_verticalalgorithm:if(n10)coutnendl;else/nistwoormoredigitslongwrite_vertical(nwiththelastdigitremoved);coutthelastdigitofnendl;,Slide14-8,CaseStudy:VerticalNumbers(cont.),TranslatingthepseudocodeintoC+n/10returnsnwiththelastdigitremoved124/10=12n%10returnsthelastdigitofn124%10=4RemovingthefirstdigitwouldbejustasvalidfordefiningarecursivesolutionItwouldbemoredifficulttotranslateintoC+,Slide14-9,Display14.1(1),Display14.1(2),TracingaRecursiveCall,write_vertical(123)if(12310)cout123endl;else/nismorethantwodigitswrite_vertical(123/10);cout(123%10)endl;,Slide14-10,Callswrite_vertical(12),resume,Output3,Functioncallends,Tracingwrite_vertical(12),write_vertical(12)if(1210)cout12endl;else/nismorethantwodigitswrite_vertical(12/10);cout(12%10)endl;,Slide14-11,Callswrite_vertical(1),resume,Output2,Functioncallends,Tracingwrite_vertical(1),write_vertical(1)if(110)cout1endl;else/nismorethantwodigitswrite_vertical(1/10);cout(1%10)endl;,Slide14-12,Simplestcaseisnowtrue,Functioncallends,Output1,ACloserLookatRecursion,write_verticalusesrecursionUsednonewkeywordsoranythingnewItsimplycalleditselfwithadifferentargumentRecursivecallsaretrackedbyTemporarilystoppingexecutionattherecursivecallTheresultofthecallisneededbeforeproceedingSavinginformationtocontinueexecutionlaterEvaluatingtherecursivecallResumingthestoppedexecution,Slide14-13,HowRecursionEnds,EventuallyoneoftherecursivecallsmustnotdependonanotherrecursivecallRecursivefunctionsaredefinedasOneormorecaseswherethetaskisaccomplishedbyusingrecursivecallstodoasmallerversionofthetaskOneormorecaseswherethetaskisaccomplishedwithouttheuseofanyrecursivecallsThesearecalledbasecasesorstoppingcases,Slide14-14,InfiniteRecursion,Afunctionthatneverreachesabasecase,intheory,willrunforeverInpractice,thecomputerwilloftenrunoutofresourcesandtheprogramwillterminateabnormally,Slide14-15,Example:InfiniteRecursion,Functionwrite_vertical,withoutthebasecasevoidnew_write_vertical(intn)new_write_vertical(n/10);coutn%100)return(power(2,0-1)*2);elsereturn(1);,Slide14-29,Functioncallends,1isreturned,Tracingpower(2,3),Power(2,3)resultsinmorerecursivecalls:power(2,3)ispower(2,2)*2Power(2,2)ispower(2,1)*2Power(2,1)ispower(2,0)*2Power(2,0)is1(stoppingcase)Seedetailsin,Slide14-30,Display14.4,Section14.2Conclusion,CanyouDeterminetheoutputofthisfunctionifcalledwithrose(4)?introse(intn)if(n0)return(power(x,n-1)*x);elsereturn(1);,Slide14-34,Reviewofpower(cont.),Eachstoppingcasereturnsthecorrectvaluepower(x,0)shouldreturnx0=1whichitdoesintpower(intx,intn)if(n0)return(power(x,n-1)*x);elsereturn(1);,Slide14-35,Reviewofpower(cont.),AllrecursivecallsreturnthecorrectvaluesothefinalvaluereturnediscorrectIfn1,recursionisused.Sopower(x,n-1)mustreturnxn-1sopower(x,n)canreturnxn-1*n=xnwhichitdoesintpower(intx,intn)if(n0)return(power(x,n-1)*x);elsereturn(1);,Slide14-36,Recursivevoid-functions,Thesamebasiccriteriaapplytocheckingthecorrectnessofarecursivevoid-functionCheckthatthereisnoinfiniterecursionCheckthateachstoppingcaseperformsthecorrectactionforthatcaseCheckthatforeachrecursivecase:ifallrecursivecallsperformtheiractionscorrectly,thentheentirecaseperformscorrectly,Slide14-37,CaseStudy:BinarySearch,AbinarysearchcanbeusedtosearchasortedarraytodetermineifitcontainsaspecifiedvalueThearrayindexeswillbe0throughfinal_indexBecausethearrayissorted,weknowa0=a1=a2last,therearenoelementsbetweenafirstandalastsokeyisnotinthissegmentanditiscorrecttosetfoundtofalseIfk=amid,thealgorithmcorrectlysetsfoundtotrueandlocationequaltomidThereforebothstoppingcasesarecorrect,Slide14-48,BinarySearchCheckingtheRecursion(cont.),Foreachcasethatinvolvesrecursion,ifallrecursivecallsperformtheiractionscorrectly,thentheentirecaseperformscorrectlySincethearrayissortedIfkeyamid,keyisinoneofelementsamid+1throughalastifitisinthearray.Nootherelementsmustbesearchedtherecursivecalliscorrect,Slide14-49,BinarySearchEfficiency,ThebinarysearchisextremelyfastcomparedtoanalgorithmthatcheckseachiteminorderThebinarysearcheliminatesabouthalftheelementsbetweenafirstandalastfromconsiderationateachrecursivecallForanarrayof100items,thebinarysearchnevercomparesmorethansevenelementstothekeyForanarrayof100items,asimpleserialsearchwillaverage50comparisonsandmaydoasmanyas100!,Slide14-50,BinarySearchAnIterativeVersion,TheiterativeversionofthebinarysearchmayberunfasteronsomesystemsThealgorithmfortheiterativeversion,showninDisplay14.8,wascreatedbymirroringtherecursivefunctionEvenifyouplananiterativefunction,itmaybehelpfultostartwiththerecursiveapproach,Slide14-51,Display14.8,ProgramExample:ARecursiveMemberFunction,AmemberfunctionofaclasscanberecursiveTheupdatefunctionfromclassBankAccountofDisplay10.6iswillbeoverloadedtocreatearecursiveversionUpdateaddsinterestforaspecifiednumberofyearstoanaccountbalance,Slide14-52,ClassBankAccountFunctionupdate,updateusesoneparameter,years,andthefollowingalgorithm:Ifthenumberofyearsis1,then(/stoppingcase)calltheotherfunctionnamedupdateIfthenumberofyearsisgreaterthan1,thenMakearecursivecalltopostyears1worthofinterestthencalltheotherupdatefunctionforoneyearsinterest,Slide14-53,Display14.9(1),Display14.9(2),FunctionupdateCheckingtheRecursion,ThereisnoinfiniterecursionEachrecursivecallreducesthenumberofyearsbyoneuntilyearsis1,astoppingcaseEachstoppingcaseperformsthecorrectactionOnestoppingcaseisyears=1.Itcallstheotherupdatefunctionwhichwaspreviouslycheckedforcorrectness,Slide14-54,FunctionupdateCheckingtheRecursion(cont.),Forthecasesthatinvolverecursion,ifallrecursivecallsperformcorrectly,theentirecaseperformscorrectly:Whenyears1,therecursivecallcorrectlypostsyears1worthofinterest,thencallstheotherupdatefunctiontopostoneadditionalyearsinterest.Theotherupdatefunctioncorrectlypostsinterestforoneyear.Thentheentireactionforyears1willbecorrect.,Slide14-55,OverloadedFunctions,Thereisnoconfusion(forthecomputer)betweenthetwoversionsofupdateWhentherecursiveversion

温馨提示

  • 1. 本站所有资源如无特殊说明,都需要本地电脑安装OFFICE2007和PDF阅读器。图纸软件为CAD,CAXA,PROE,UG,SolidWorks等.压缩文件请下载最新的WinRAR软件解压。
  • 2. 本站的文档不包含任何第三方提供的附件图纸等,如果需要附件,请联系上传者。文件的所有权益归上传用户所有。
  • 3. 本站RAR压缩包中若带图纸,网页内容里面会有图纸预览,若没有图纸预览就没有图纸。
  • 4. 未经权益所有人同意不得将文件中的内容挪作商业或盈利用途。
  • 5. 人人文库网仅提供信息存储空间,仅对用户上传内容的表现方式做保护处理,对用户上传分享的文档内容本身不做任何修改或编辑,并不能对任何下载内容负责。
  • 6. 下载文件中如有侵权或不适当内容,请与我们联系,我们立即纠正。
  • 7. 本站不保证下载资源的准确性、安全性和完整性, 同时也不承担用户因使用这些下载资源对自己和他人造成任何形式的伤害或损失。

评论

0/150

提交评论