版权说明:本文档由用户提供并上传,收益归属内容提供方,若内容存在侵权,请进行举报或认领
文档简介
1
TheProgrammingLayer2OutlineConceptsDefinitionHowtodevelopanalgorithmEssentialfeaturesThreeConstructsAlgorithmRepresentationPseudocodeBasicalgorithms
3OutlineEvolutionCategoriesoflanguages Buildingprograms4ObjectivesDefinealgorithms.Listthe5essentialpropertiesofanalgorithm.Defineandusethethreeconstructsfordeveloping
algorithms:sequence,decision,andrepetition.Understandandusetoolstorepresentalgorithms:pseudocodeUnderstandtheconceptofmodularityandsubalgorithms.Listandcomprehendcommonalgorithms,suchassortingandsearching.5ObjectivesHaveavisionofcomputerlanguageevolution.Distinguishbetweenmachine,assembly,andhigh-levellanguages.Distinguishbetweenthedifferentcategoriesoflanguages:procedural,object-oriented,functional,declarative,andspecial.Understandtheprocessofcreatingandrunningaprogram.6part1
DEFINITION7Informaldefinition8Example--Findingthelargestinteger
amongfiveintegers9Definingactions10Refinement2problemswiththepreviousmethod:Theactioninthefirststepisdifferentfromtheonesfortheothersteps.Thewordingisnotthesameinsteps2to5.11Generalization12FormaldefinitionAlgorithm:anorderedsetofunambiguousstepsthatproducesaresultandterminatesinafinitetime.Itisastep-by-stepproblem-solvingprocedure,especiallyanestablished,recursivecomputationalprocedureforsolvingaprobleminafinitenumberofsteps.Itisaprecise,systematicmethodforproducingaspecifiedresult.135essentialpropertiesofalgorithmsTowritealgorithmsthatarespecifiedwellenoughforacomputertofollow,makesureeveryalgorithmhasfiveessentialproperties:InputsspecifiedOutputsspecifiedDefinitenessEffectivenessFiniteness14InputspecifiedTheinputsarethedatathatwillbetransformedduringthecomputationtoproducetheoutput.Wemustspecifythetypeofthedata,theamountofdata,andtheformthatthedatawilltake.Supposethealgorithmisarecipe.Wemustlisttheingredients(typeofinputs),theirquantities(amountofinput),andtheirpreparation,ifany(formofinputs),asin“1/4cuponion,minced.”15OutputsspecifiedTheoutputsarethedataresultingfromthecomputation,theintendedresult.Oftenthedescriptionisgiveninthenameofthealgorithm,asin“Algorithmtocomputeabattingaverage.”Aswithinputs,wemustspecifythetype,amount,andanyformoftheoutputs.“3dozen3-inchchocolatechipcookies.”Apossibleoutputforsomecomputationisastatementthattherecanbenooutput—thatis,nosolutionispossible.16DefinitenessAlgorithmsmustspecifyeverystep.
Definitenessmeansspecifyingthesequenceofoperationsfortransformingtheinputsintotheoutputs.Everydetailofeachstepmustbespelledout,includinghowtohandleerrors.Definitenessensuresthatifthealgorithmisperformedatdifferenttimesorbydifferentagents(peopleorcomputers)usingthesamedata,theoutputwillbethesame.17EffectivenessItmustbepossiblefortheagenttoexecutethealgorithmmechanicallywithoutanyfurtherinputs,specialtalent,clairvoyance,creativity,helpfromSuperman,andsoon.Whereasdefinitenessspecifieswhichoperationstodo,effectivenessmeansthattheyaredoable.Examplesofineffectiveness:“Entertheamountofincomeyouwouldhavereceivedthisyearhadyouworkedharder”18FinitenessAnalgorithmmusthavefiniteness;itmusteventuallystop,eitherwiththerightoutputorwithastatementthatnosolutionispossible.Ifnoanswercomesback,wecan’ttellwhetherthealgorithmisstillworkingonananswerorisjustplain“stuck”.Finitenessbecomesanissueforcomputeralgorithmsbecauseifthealgorithmdoesn’tspecifywhentostoptherepetition,thecomputerwillcontinuetorepeattheinstructionsforever.Forexample,divide3into10.Anyprocesshavingthesefivepropertieswillbecalledanalgorithm.19part2
3CONSTRUCTS203ConstructsComputerscientistshavedefinedthreeconstructsforastructuredprogramoralgorithm.Theideaisthataprogrammustbemadeupofacombinationofonlythesethreeconstructs:sequence,decision(selection),andrepetition.21SequenceAnalgorithm,andeventuallyaprogram,isasequenceofinstructions,whichcanbeasimpleinstructionoreitheroftheothertwoconstructs.Aprogramisanalgorithmthathasbeencustomizedtosolveaspecifictaskunderaspecificsetofcircumstancesinaspecificlanguage.22Decision23RepetitionInsomeproblems,thesamesequenceofinstructionsmustberepeated.Youhandlethiswiththerepetition(loop)construct.24part3
AlgorithmRepresentation25AlgorithmRepresentationWecanusedifferenttoolstorepresentalgorithms:Pseudo-code26PseudocodeItisanEnglish-likerepresentationofthecoderequiredforanalgorithm.ItispartEnglishandpartstructuredcode.Englishpartprovidesarelaxedsyntaxthatiseasytoread.Codepartconsistsofanextendedversionofthebasicalgorithmicconstructs(sequence,decisionandrepetition).Untilnow,thereisnostandardforpseudocode.27PseudocodeexampleAlgorithm:FindingSmallestPurpose:Thisalgorithmfindsthesmallestnumberamongalistofnumbers.Pre:ListofnumbersPost:NoneReturn:TheSmallest1.Setsmallesttothefirstnumber2.loop(notendoflist)2.1if(nextnumber<smallest)2.1.1setsmallesttonextnumber2.2endif3.endloop4.ReturnsmallestEndfindingSmallest28PseudocodeAnalgorithmwritteninpseudocodecanbedecomposedintoseveralelementsandconstructs.
Header:namethealgorithm.Purpose,precondition,postconditionandreturn:Thepurposeisashortstatementaboutwhatthealgorithmdoes;Thepreconditionlistsanyrequirements;Thepostconditionidentifiesanyeffectcreated;Thereturnshowswhatisreturnedfromthealgorithm.Ifthereisnothingtobereturned,thenullshouldbespecified.
Statementnumbers:listexecutionorder.
Statementconstructs:basedonthreeconstructs. 29PseudocodeExample1WriteanalgorithminpseudocodethatfindstheaverageoftwonumbersSolution
AverageOfTwo
Input:
TwonumbersAddthetwonumbersDividetheresultby2Returntheresultofstep2
EndExample2Writeanalgorithmtochangeanumericgradetoapass/nopassgrade.Solution
Pass/NoPassGrade
Input:
Onenumberif(thenumberisgreaterthanorequalto60)
then1.1Setthegradeto“pass”else1.2Setthegradeto“nopass”EndifReturnthegrade
EndExample3Writeanalgorithmtochangeanumericgradetoalettergrade.Solution
LetterGrade
Input:
Onenumber1. if(thenumberisbetween90and100,inclusive)
then1.1Setthegradeto“A”Endif2. if(thenumberisbetween80and89,inclusive)
then2.1Setthegradeto“B”Endif…Seepage148Example4Writeanalgorithmtofindthelargestofasetofnumbers.Youdonotknowthenumberofnumbers.Solution
FindLargest
Input:
AlistofpositiveintegersSetLargestto0while(moreintegers)
2.1if(theintegerisgreaterthanLargest)
then
2.1.1Setlargesttothevalueoftheinteger
Endif
EndwhileReturnLargest
EndExample5Writeanalgorithmtofindthelargestof1000numbers.Solution
FindLargest
Input:
1000positiveintegersSetLargestto0SetCounterto0while(Counterlessthan1000)
3.1if(theintegerisgreaterthanLargest)
then
3.1.1SetLargesttothevalueoftheinteger
Endif
3.2IncrementCounter
EndwhileReturnLargest
End35SubprogramsTheprinciplesofstructuredprogrammingrequirethatanalgorithmbebrokenintosmallunitscalledsubalgorithms(thetermsubprograms,subroutines,procedures,functions,methods,andmodulesarealsoused).Eachsubalgorithmisinturndividedintosmallersubalgorithms.Theprocesscontinuesuntilthesubalgorithmbecomeintrinsic(understoodeasily).36SubprogramsWecandivide“AlgorithmFindLargest”intoamainalgorithmandasubalgorithm.Ineachiteration,thealgorithmfindsthelargeroftwointegers.Wecanseparatethispartofthetaskandcreateasmallsubtaskoutofit.37SubprogramsInline2.1,FindLargestissuspendedandFindLargerbegins.FindLargerfindsthelargernumberbetweenthecurrentLargestvalueandthecurrentintegervalue.Thisisknownasafunctioncall.Notethatineachiteration,FindLargeriscalledonce.Theadvantagesofusingsubalgorithms:Itismoreunderstandable.Asubalgorithmcanbecalledmanytimesindifferentpartsofthemainalgorithmwithoutbeingrewritten.38Subprograms
FindLargest Input:
AlistofpositiveintegersSetLargestto0while(moreintegers)
2.1FindLarger
EndwhileReturnLargest
End
FindLarger Input:
Largestandcurrentintegerif(theintegerisgreaterthanLargest)
then
1.1SetLargesttothevalueoftheinteger
Endif
End39Example40Example2.
Writeanalgorithmforasimplecalculator(in
pseudocode
and
structurechart).Pseudocode:Gettwonumbersandtheoperationdesired.Checktheoperation:2.1Ifoperationisaddition,theresultisthefirst+thesecond;2.2Ifoperationissubtraction,theresultisthefirst-thesecond;2.3Ifoperationismultiplication,theresultisthefirst*thesecond;2.4Ifoperationisdivision,checkthesecondnumber:
2.4.1Ifzero,senderrormessage. 2.4.2Ifnotzero,thefirst/thesecond.Printouttheresultortheerrormessage.41Example3.Writeanalgorithminpseudocodeforaprogramtocalculatetheareaofsimpleshapes(rectangle,righttriangleandcircle).Gettheshapedesired.Ifitisarectangle:2.1getthelengthandwidth.2.2calculatetheareaaslength*width.Ifitisarighttriangle:3.1getthebaseandheight.3.2calculatetheareaasbase*height/2.Ifitisacircle:4.1gettheradius.4.2calculatetheareaasradius*radius*3.14.Printoutthearea.42part4
BasicAlgorithms43Summation44Product45SortingSortingistheprocessbywhichdataarearrangedaccordingtotheirvalues.Therearethreefundamentalsortingalgorithms:SelectionsortBubblesortInsertionsort46SelectionsortInselectionsort,thelistisdividedinto2sublists—sortedandunsorted—whicharedividedbyanimaginarywall.Youfindthesmallestelementfromtheunsortedsublistandswapitwiththeelementatthebeginningoftheunsorteddata.Aftereachselectionandswapping,theimaginarywallmovesoneelementahead,increasingthenumberofsortedelementsanddecreasingthenumberofunsortedones.Eachtimeyoumoveoneelementfromtheunsortedsublisttothesortedsublist,youhavecompletedasortpass.Alistofnelementsrequiresn-1passestocompletelyrearrangethedata.47484950BubblesortInbubblesortmethod,thelistisdividedinto2sublists—sortedandunsorted.Thesmallestelementisbubbledfromtheunsortedsublistandmovedtothesortedsublist.Afterthesmallestelementhasbeenmovedtothesortedlist,thewallmovesoneelementahead.Eachtimeanelementmovesfromtheunsortedsublisttothesortedsublist,onesortpassiscompleted.Givenalistofnelements,bubblesortrequiresupton-1passestosortthedata.5152InsertionsortIninsertionsortmethod,thelistisdividedinto2sublists—sortedandunsorted.Ineachpass,thefirstelementoftheunsortedsublistispickedup,transferredtothesortedlist,andinsertedattheappropriateplace.Notethatalistofnelementswilltakeatmostn-1passestosortthedata.5354SearchingSearchingistheprocessoffindingthelocationofatargetamongalistofobjects.Inthecaseofalist,searchingmeansthatgivenavalue,youwanttofindthelocation(index)ofthefirstelementinthelistthatcontainsthatvalue.55SequentialsearchSequentialsearchisusedifthelistbeingsearchedisnotordered.Inasequentialsearch,youstartsearchingforthetargetfromthebeginningofthelist.Youcontinueuntilyoueitherfindthetargetoryouaresurethatitisnotinthelist(becauseyouhavereachedtheendofthelist).5657Binarysearch58part6
Evolution59EvolutionAcomputerlanguageisasetofpredefinedwordsthatarecombinedintoaprogramaccordingtopredefinedrules(syntax).Computerlanguageshaveevolvedfrommachinelanguagetonaturallanguages.60MachinelanguagesMachinelanguage,thelowestleveloflanguage,isthebasiclanguageofthecomputer,representingdataas1sand0s.Machineprogramsvaryfromcomputertocomputer;thatis,theyaremachinedependent.Theonlylanguageunderstoodbyacomputerismachinelanguage.Thesebinarydigitscorrespondtotheonandoffelectricalstatesofthecomputer.61MachinelanguagesAdvantage:itworksefficientlyforcomputer.Disadvantage:itisnotconvenientforpeopletoreadanduse.1234567891011121314151662SymboliclanguagesSymboliclanguage,alsocalledassemblylanguage,isalow-levellanguagethatallowsaprogrammertouseabbreviationsoreasilyrememberedwordsinsteadofnumbers.Assemblylanguagevariesfromcomputertocomputer;it’smachinedependent.Aprogrammercanwriteinstructionsinassemblylanguagemorequicklythaninmachinelanguage;however,it’sstillnotaneasyonetolearn,andit’ssotedioustousethatmistakesarefrequent.63Symboliclanguages12345678910111213141516Entry main, ^m<r2>subl2 #12,spjsb C$MAIN_ARGSmovab $CHAR_STRING_CONpushal -8(fp)pushal (r2)calls #2,readpushal -12(fp)pushal 3(r2)calls #2,readmull3 -8(fp),-12(fp),-pushal 6(r2)calls #2,printclrl r0ret64LanguagetranslatorsAspecialprogramcalledanassemblerisusedtotranslatesymboliccodeintomachinelanguage.Alanguagetranslatorisatypeofsystemsoftwarethattranslatesaprogramwritteninasecond-orhigher-generationlanguageintomachinelanguage.65LanguagetranslatorsLanguagestranslatorsareofthreetypes:AssemblersCompilersInterpreters SourceCodeObjectCodeLanguageTranslator66High-levellanguagesAhighlevellanguageisanEnglish-likelanguagethatallowsuserstowriteinafamiliarnotation,ratherthannumbersorabbreviations.Mosthigh-levellanguagesarenotmachinedependent;theycanbeusedonmorethanonekindofcomputers.Theyareportable,allowingtheprogrammertoconcentrateontheapplicationratherthantheintricaciesofthecomputer.67High-levellanguagesThetranslatorforhigh-levellanguagesisdependingonthelanguage,eitheracompileroraninterpreter.Compiler—executelater.It’ssoftwarethatlooksatanentirehigh-levelprogrambeforetranslatingitintomachinelanguage.ExamplesareCandCOBOL.Interpreter—executeimmediately.It’ssoftwarethatconvertshigh-levellanguagestatementsintomachinelanguageoneatatime,insuccession.ExamplesareBASICandLISP.68NaturallanguagesNaturallanguagesareoftwotypes.Thefirstareordinaryhumanlanguages(suchasChinese,English,Spanishandsoon).Thesecondareprogramminglanguagesthatusehumanlanguagetogivepeopleamorenaturalconnectionwithcomputer.Naturallanguagesarepartofthefieldofstudyknownasartificialintelligence(AI).69part7
Categoriesoflanguages70CategoriesoflanguagesWedividecomputerlanguagesintofivecategories:71ProcedurallanguagesAprocedurallanguageisasetofinstructionsthatareexecutedonebyonefrombeginningtoendunlessaninstructionforcesthecontrolelsewhere.Whenprogrammersneedtosolveaproblemusingoneoftheprocedurallanguages,theyshouldknowtheproceduretofollow.Becauseeachinstructionofprocedurallanguagesisacommandtothecomputersystemtodosomespecifictask,procedurallanguagessometimescalledimperativelanguages.72ProcedurallanguagesFORTRAN(FORmulaTRANslation)COBOL(CommonBusiness-OrientedLanguagePascalCAda73Object-orientedlanguagesUnlikeCandPascalareproceduralorientedlanguages,forcingtheusertofollowapredeterminedpathfromstepAtoStepBandsoon,object-orientedlanguagesareeventdriven—thatis,theyrespondtoinput
温馨提示
- 1. 本站所有资源如无特殊说明,都需要本地电脑安装OFFICE2007和PDF阅读器。图纸软件为CAD,CAXA,PROE,UG,SolidWorks等.压缩文件请下载最新的WinRAR软件解压。
- 2. 本站的文档不包含任何第三方提供的附件图纸等,如果需要附件,请联系上传者。文件的所有权益归上传用户所有。
- 3. 本站RAR压缩包中若带图纸,网页内容里面会有图纸预览,若没有图纸预览就没有图纸。
- 4. 未经权益所有人同意不得将文件中的内容挪作商业或盈利用途。
- 5. 人人文库网仅提供信息存储空间,仅对用户上传内容的表现方式做保护处理,对用户上传分享的文档内容本身不做任何修改或编辑,并不能对任何下载内容负责。
- 6. 下载文件中如有侵权或不适当内容,请与我们联系,我们立即纠正。
- 7. 本站不保证下载资源的准确性、安全性和完整性, 同时也不承担用户因使用这些下载资源对自己和他人造成任何形式的伤害或损失。
最新文档
- JJF 2464-2026可吸附有机卤素测定仪校准规范
- T/SHBX 053-2025全生物降解食品接触用一次性手套
- T/PPZL 039-2025黄河流域内蒙古段草地生态系统服务价值评估技术规程
- T/CECCEDA 8-2026人工智能 数据资产可信流通管理框架
- T/CHASA 017-2024家电上门服务全流程用户体验评价规范
- T/CSMT-YB 018-2026γ射线成像探测系统检测规范
- GB/T 591-2026船用法兰铸铁截止止回阀
- 2025~2026学年河北省廊坊市校联考冀教版六年级上册第三次月考数学试卷【附答案】
- 江苏省新沂市度第二期期2027届数学七上期末联考模拟试题含解析
- PHP工程师经典面试题(含详细答案解析)
- 2026年新版gcp考试题库及答案pdf
- 小学四年级道德与法治教学设计:单元整体教学视域下《反对浪费》大单元实践探索
- 精神卫生行业精神科医师精神诊疗规范手册(执行版)
- 2026年10月自考04842产品系统化设计押题及答案(北京)
- E三相异步电动机的运行维护与故障处理
- 《“探界者”钟扬》2026-2027学年统编版高一语文必修上册
- 2025 中国过敏性休克急救指南(中文版)完整原文 + 肾上腺素使用规范
- 被执行人财产申报表(官方标准完整版)
- 市政道路工程试验检测计划
- 第19课《想和做》课件 2026-2027学年统编版语文九年级上册
- 2026年食品安全总监管理员考试题库
评论
0/150
提交评论