csc118 topic 2
-
Upload
red-september-ii -
Category
Documents
-
view
25 -
download
0
description
Transcript of csc118 topic 2
-
CSC118FUNDAMENTALSOFALGORITHMDEVELOPMENTChapter2:IntroductiontoProblemSolvingUsingComputerA. ProblemSolving
1. Whatisproblem?
Unsettled matter demanding solutions or decision and requiring usually considerablethoughtorskillforitspropersolutionordecision
2. Whatissolution?
Anactionorprocessofsolvingaproblem,also; Thefactorstateofaproblembeingsolved,also; Ananswertoormeansofansweringaproblem.
From the definition, the problem and solution are interrelated and thereforewe believe that aproblem should not be investigated separately from its solution. Therefore, to solve a problem,
threeimportantstepsshouldbeperformed:
i. Understandtheproblemthoroughly
ii. Understandtheconditionsandrequirementsoftheproblem
iii. Searchforalternativesolutionsandselectageneralsolution
3. Arecomputersintelligence?
Computersareverypowerfulmachinesbutlikeothermachinespossesnointelligence.Theyprogrammedtosolveproblems.
4. Whatisaprogram?
Aprogram isa setof instructionswhichare commands to computers toperform specificoperationsondata. Instructionswithinaprogramareorganized in suchaway,when the
programisrunonacomputer;itresultsinthesolutionofaproblem.
5. Whatisaprogrammer?
Peoplewhowriteprogramsforcomputersarecalledprogrammers. It istheprogrammersresponsibility to write a correct program since a computer only faithfully obeys the
commandsspecifiedbytheinstructions;itdoesnotcorrectthemiftheyareinerror.Ifthe
programisnotcorrect,erroneousresultsareobtained.
-
CSC118FUNDAMENTALSOFALGORITHMDEVELOPMENTChapter2:IntroductiontoProblemSolvingUsingComputer
Toproduce a correctprogram, aprogrammer goes through two (2)differentbut relatedphases:theproblemsolvingphaseandtheprogrammingphase.
a. Problemsolvingphase:
i. First, acquire a thorough understanding of the nature of the problem, and
deriveitsspecificationandrequirement.
ii. Next,determine andorganize theorderofoperation and computation to be
performedtosolvetheproblem.
Theoutputof theproblemsolvingphase is theproblem solution in someacceptablerepresentationalformsuchasadescription inhighlystructured
English(pseudocode)oraflowchart.Thisistheonewhatwecalledsolution
algorithmorforshort,analgorithm.
b. Programmingphase(Implementationphase):
i. Write the instructions for performing the predetermined operation and
computationsusingsuitableprogramminglanguage.
The result is a computer program, which is run on a computer and anyerrorsdiscoveredarecorrected.
A correct program is thus obtained and is ready to be used wheneverrequired.
B. WhatisAlgorithm?
Thereisnogeneraldefinitionofalgorithmaccepted. Butwecansaythatalgorithmis:
i. Astepbystepproblemsolvingprocedure
ii. Asequenceofinstructionthattellhowtosolveaparticularproblem.
iii. Asetofinstructionforsolvingaproblem,especiallyonacomputer.
iv. Acomputablesetofstepstoachieveadesiredresult.
However,mostagreethatalgorithmhassomethingtodowithdefininggeneralizedprocessestogetoutputfromtheinput.
-
CSC118FUNDAMENTALSOFALGORITHMDEVELOPMENTChapter2:IntroductiontoProblemSolvingUsingComputer
Therefore,wecanconcludethat:o Algorithm a stepbystepproblem solvingprocess inwhicha solution isarrived ina
finiteamountoftime,OR
o Analgorithmisafinitelistofsequentialstepsspecifyingactionsthatifperformedresultinsolutionofaspecificproblem.
C. HistoryofAlgorithm
ThewordAlgorithmcomesfromthenameoffamousPersianmathematician,AbuJafarMohammedIbnMusaAlKhowarizmi(A.D.825).Heisknownforhisextensiveworkinalgebra.
D. RequirementofAlgorithm
Thealgorithmshouldbehasthefollowingrequirement:i. Finiteness
ii. Definiteness
iii. Effectiveness
iv. Input
v. Output
1. Finiteness
Analgorithmmusteventuallyhalt(endup)afteritsstepshavebeenperformedafinitenumberoftimes.
Analgorithmthatisnotguaranteedtohaltcannotbeimplementedbyeitherhumansormachines.
Example:Whathappenedifwearenonstoppourwaterinaglass?
2. Definiteness
Everyactionspecifiedatanystepofanalgorithmmustbepreciselydefined. Everyactioncontainedinanalgorithmmustbeclearandnotsubjecttodifferent
interpretations.Inotherwords,eachactiondescribedmustbeunambiguous.
Forexample:GivengrammarEE+E|E*E.WhathappenifwederivesententialformE+E*EfromproductionE?
-
CSC118FUNDAMENTALSOFALGORITHMDEVELOPMENTChapter2:IntroductiontoProblemSolvingUsingComputer
3. Effectiveness
Everysteporactionspecifiedinanalgorithmmustbeexecutable. Example:
a. CanweconverttemperaturefromFahrenheittoCelsius?
b. CanweconvertcurrencyfromUSDtoRM?
c. Canwesort100numbersinascendingorder?
4. Input
Analgorithmmayreceiveinputsfromoutside. Example:Calculatetheareaofonecircle.Whatistheinput?
5. Output
Analgorithmmustproduceoneormoreoutput. Example:Calculatetheareaofonecircle.Whatistheoutput?
E. AlgorithmandLogicalThinking
Todevelopthealgorithm,theprogrammerneedstoask:1. Whatdatahastobefedintothecomputer?
2. WhatinformationdoIwanttogetoutofthecomputer?
3. Logic:Planningtheprocessingoftheprogram.Itcontainstheinstructionsthatcausethe
inputdatatobeturnedintothedesiredoutputdata.
F. SearchingAlgorithm
Searchingalistforagivenitemisoneofthemostcommonoperationsperformedonlistorarray.
Tosearchthelist,weneedthepiecesofinformationwhichare:1. Thelist.
Forexample:a. Abookcontainingapagesnumbers.
b. Arraycontainingalistofelements.
-
CSC118FUNDAMENTALSOFALGORITHMDEVELOPMENTChapter2:IntroductiontoProblemSolvingUsingComputer
2. Thelengthoflist.
Forexample:a. Bookhasthenumberofpagesfrom1toN.
b. Arrayconsistoffinitenumberofelements,i.eE=[1,2,3,,N].
3. Theitemforwhichwearesearchingfor.
Forexample:a. Wewanttosearchpagenumber4inabook.
b. Searchnumber3fromelementofarray,E=[1,2,3,N].
Afterthesearchiscompleted:4. IftheitemisfoundreportSuccessandreportthelocationwheretheitemisfound.
5. Iftheitemisnotfound,thereportfailure.
Therefore,toaccommodate4and5,wewillwriteafunctionorprocedurethatreturnavalue. Ifthesearchitemisfoundinthelist,thefunctionorprocedurereturnsthelocationin
thelistwherethesearchitemisfound.
Otherwise,itreturn1,indicatingthatthesearchingisunsuccessful.
Fromthisoutput(locationoftheitembeingsearch,and1),itisclearthatthevaluereturningfunction(procedure),hasthree(3)parameters.
1. Thearraythatcontainingthelist,letwewriteaslist.
2. Thelengthofthelist,letwewriteaslistLength.(notethatthelistLength
-
CSC118FUNDAMENTALSOFALGORITHMDEVELOPMENTChapter2:IntroductiontoProblemSolvingUsingComputerG. ProblemSolvingusingDifferentAlgorithm(LinearSearchAlgorithmandBinarySearchAlgorithm)
Forinstance,wesearchspecificpageinabookusingmethod:1. Linearsearchoralsoknownsequentialsearchalgorithm.
2. Binarysearchalgorithmoralsoknownchopalgorithm.
Weknowthatpagenumberinabookisinsequence.Howisthealgorithmtofindtheparticularpageinabook?
Whatinformationdoweneed? Listofpageofabook,List. Numbersofpageofabook,listLength.(listLength
-
CSC118FUNDAMENTALSOFALGORITHMDEVELOPMENTChapter2:IntroductiontoProblemSolvingUsingComputer
Pseudocode:
Problem:Searchpage(list[],listLength,searchItem)found=FALSElist[]={1,2,3,4,5,6,7,8,9,10}listLength=10searchItem=4loc01.Start2.DOWHILEloc
-
CSC118FUNDAMENTALSOFALGORITHMDEVELOPMENTChapter2:IntroductiontoProblemSolvingUsingComputerI. BinarySearch
Abinarysearchusesthedivideandconquertechniquetosearchthelist.1. First,searchItemiscomparedwiththemiddleelementofthelist.
a. IFthesearchItemislessthanthemiddleelementofthelist,werestrictthe
searchtothelowerhalfofthelist.
b. ELSE,wesearchtheupperhalfofthelist
Whatinformationdoweneed?1. Listofpageofabook,List.
2. Numbersofpageofabook,listLength.(listLength
-
CSC118FUNDAMENTALSOFALGORITHMDEVELOPMENTChapter2:IntroductiontoProblemSolvingUsingComputer
PseudocodeProblem:Searchpage(list[],listLength,searchItem)found=FALSElist[]={1,2,3,4,5,6,7,8,9,10}listLength=10searchItem=4first=0last=listLength11.Start2.DOWHILEfirstsearchItem last=middle1 ELSE first=middle+1 ENDIFENDDO3.IFfoundisTRUE returnandreportthemiddleELSEreturn1ENDIF4.Stop
IterationofbinarysearchIteration first last middle list[middle] Found
1 0 9 4 5 FALSE2 0 3 1 2 FALSE3 2 3 2 3 FALSE4 3 3 3 4 TRUE
-
CSC118FUNDAMENTALSOFALGORITHMDEVELOPMENTChapter2:IntroductiontoProblemSolvingUsingComputerJ. BubbleSort
PseudocodeBubbleSort(list[],listLength)iteration1index01.Start2.DOWHILEiteration