You are on page 1of 10

CSC118FUNDAMENTALSOFALGORITHMDEVELOPMENT

Chapter2:IntroductiontoProblemSolvingUsingComputer

A. ProblemSolving
1. Whatisproblem?

Unsettled matter demanding solutions or decision and requiring usually considerable


thoughtorskillforitspropersolutionordecision

2. Whatissolution?

Anactionorprocessofsolvingaproblem,also;

Thefactorstateofaproblembeingsolved,also;

Ananswertoormeansofansweringaproblem.

From the definition, the problem and solution are interrelated and therefore we believe that a
problem should not be investigated separately from its solution. Therefore, to solve a problem,
threeimportantstepsshouldbeperformed:
i.

Understandtheproblemthoroughly

ii. Understandtheconditionsandrequirementsoftheproblem
iii. Searchforalternativesolutionsandselectageneralsolution

3. Arecomputersintelligence?

Computersareverypowerfulmachinesbutlikeothermachinespossesnointelligence.They
programmedtosolveproblems.

4. Whatisaprogram?

A program is a set of instructions which are commands to computers to perform specific


operations on data. Instructions within a program are organized in such a way, when the
programisrunonacomputer;itresultsinthesolutionofaproblem.

5. Whatisaprogrammer?

Peoplewhowriteprogramsforcomputersarecalledprogrammers.Itistheprogrammers
responsibility to write a correct program since a computer only faithfully obeys the
commandsspecifiedbytheinstructions;itdoesnotcorrectthemiftheyareinerror.Ifthe
programisnotcorrect,erroneousresultsareobtained.

CSC118FUNDAMENTALSOFALGORITHMDEVELOPMENT
Chapter2:IntroductiontoProblemSolvingUsingComputer

To produce a correct program, a programmer goes through two (2) different but related
phases:theproblemsolvingphaseandtheprogrammingphase.

a. Problemsolvingphase:
i.

First, acquire a thorough understanding of the nature of the problem, and


deriveitsspecificationandrequirement.

ii.

Next, determine and organize the order of operation and computation to be


performedtosolvetheproblem.

The output of the problemsolving phase is the problem solution in some


acceptablerepresentationalformsuchasadescriptioninhighlystructured
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 any


errorsdiscoveredarecorrected.

A correct program is thus obtained and is ready to be used whenever


required.

B. WhatisAlgorithm?

Thereisnogeneraldefinitionofalgorithmaccepted.

Butwecansaythatalgorithmis:
i.

Astepbystepproblemsolvingprocedure

ii. Asequenceofinstructionthattellhowtosolveaparticularproblem.
iii. Asetofinstructionforsolvingaproblem,especiallyonacomputer.
iv. Acomputablesetofstepstoachieveadesiredresult.

However,mostagreethatalgorithmhassomethingtodowithdefininggeneralizedprocessesto
getoutputfromtheinput.

CSC118FUNDAMENTALSOFALGORITHMDEVELOPMENT
Chapter2:IntroductiontoProblemSolvingUsingComputer

Therefore,wecanconcludethat:
o

Algorithm a stepbystep problem solving process in which a solution is arrived in a


finiteamountoftime,OR

Analgorithmisafinitelistofsequentialstepsspecifyingactionsthatifperformedresult
insolutionofaspecificproblem.

C. HistoryofAlgorithm

ThewordAlgorithmcomesfromthenameoffamousPersianmathematician,AbuJafar
MohammedIbnMusaAlKhowarizmi(A.D.825).Heisknownforhisextensiveworkinalgebra.

D. RequirementofAlgorithm

Thealgorithmshouldbehasthefollowingrequirement:
i.

Finiteness

ii. Definiteness
iii. Effectiveness
iv. Input
v. Output

1. Finiteness

Analgorithmmusteventuallyhalt(endup)afteritsstepshavebeenperformedafinite
numberoftimes.

Analgorithmthatisnotguaranteedtohaltcannotbeimplementedbyeitherhumansor
machines.

Example:Whathappenedifwearenonstoppourwaterinaglass?

2. Definiteness

Everyactionspecifiedatanystepofanalgorithmmustbepreciselydefined.

Everyactioncontainedinanalgorithmmustbeclearandnotsubjecttodifferent
interpretations.Inotherwords,eachactiondescribedmustbeunambiguous.

Forexample:GivengrammarEE+E|E*E.WhathappenifwederivesententialformE
+E*EfromproductionE?

CSC118FUNDAMENTALSOFALGORITHMDEVELOPMENT
Chapter2: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

Searchingalistforagivenitemisoneofthemostcommonoperationsperformedonlistor
array.

Tosearchthelist,weneedthepiecesofinformationwhichare:
1. Thelist.

Forexample:
a. Abookcontainingapagesnumbers.
b. Arraycontainingalistofelements.

CSC118FUNDAMENTALSOFALGORITHMDEVELOPMENT
Chapter2: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),itisclearthatthevaluereturning
function(procedure),hasthree(3)parameters.
1. Thearraythatcontainingthelist,letwewriteaslist.
2. Thelengthofthelist,letwewriteaslistLength.(notethatthelistLength<=arraySize
andarraySizeisanumberofelementsinarray).
3. Theitemforwhichwearesearching,letwewriteassearchItem.

CSC118FUNDAMENTALSOFALGORITHMDEVELOPMENT
Chapter2:IntroductiontoProblemSolvingUsingComputer

G. ProblemSolvingusingDifferentAlgorithm(LinearSearchAlgorithmandBinarySearchAlgorithm)

Forinstance,wesearchspecificpageinabookusingmethod:
1. Linearsearchoralsoknownsequentialsearchalgorithm.
2. Binarysearchalgorithmoralsoknownchopalgorithm.

Weknowthatpagenumberinabookisinsequence.Howisthealgorithmtofindtheparticular
pageinabook?

Whatinformationdoweneed?

Listofpageofabook,List.

Numbersofpageofabook,listLength.(listLength<=arraySize,wherearraysizeisrefer
tonumbersofpageofabook).

Pagethatwearesearchingfor,searchItem.

LinearSearch

Example:Findpage4ofaC++bookthathas10numbersofpages.

Whatisinthelist:
a. List[]={1,2,3,4,5,6,7,8,9,10}.
b. Wherelocation,locof1isinlist[0],locof2isinlist[1]andsoforth.

WhatisthelistLength?
a. listLength=10.

WhatisthesearchItem?
a. searchItem=4.

CSC118FUNDAMENTALSOFALGORITHMDEVELOPMENT
Chapter2:IntroductiontoProblemSolvingUsingComputer

Pseudocode:

Problem:Searchpage(list[],listLength,searchItem)
found=FALSE
list[]={1,2,3,4,5,6,7,8,9,10}
listLength=10
searchItem=4
loc0

1.Start
2.DOWHILEloc<listLength&&foundisFALSE

IFlist[loc]==searchItem

found=TRUE

ENDIF
ENDDO
3.IFfoundisTRUE

returnandreportthelocation,loc
ELSE

return1//indicatethatthesearchItemisnotfound
ENDIF
5.Stop

Iterationofsequential(linear)searching
Iteration

loc

list[loc]

3
4

list[loc]==searchItem

found

Nextloc

1==4isfalse

false

loc=1

2==4isfalse

false

loc=2

3==4isfalse

false

loc=3

4==4istrue

true

Sinceconditionof4==4istrueandflagfoundistrue,thereforethelocationof4whichislist
[3]willbereportedandreturned.

H. PerformanceofLinearSearchComparedtoBinarySearch

Sequentialsearchperformssomewhatbetteronasortedlistbutisstillnotveryefficientfor
largelists.

However,thereisanothersearchalgorithmthatismuchfasterthatsequentialalgorithmcalled
binarysearchalgorithm.
i.

Itistypicallysearchesabouthalfthelist.

ii. Toapplybinarysearchalgorithmthelistmustbelisted,justlikesequentialalgorithm.

CSC118FUNDAMENTALSOFALGORITHMDEVELOPMENT
Chapter2:IntroductiontoProblemSolvingUsingComputer

I.

BinarySearch

Abinarysearchusesthedivideandconquertechniquetosearchthelist.
1. First,searchItemiscomparedwiththemiddleelementofthelist.
a. IFthesearchItemislessthanthemiddleelementofthelist,werestrictthe
searchtothelowerhalfofthelist.
b. ELSE,wesearchtheupperhalfofthelist

Whatinformationdoweneed?
1. Listofpageofabook,List.
2. Numbersofpageofabook,listLength.(listLength<=arraySize,wherearraysizeisrefer
tonumbersofpageofabook).
3. Pagethatwearesearchingfor,searchItem.
4. Locationoffirstpage,first,middlepage,middleandlastpage,lastbecausewealways
dividethenumberofpagesinto2parts(binary).

Example:Findpage4ofaC++bookthathas10numbersofpages.

Whatisthelist?
a. list[]={1,2,3,4,5,6,7,8,9,10}.Wherelocation,locof:
b. locof1isinlist[0],locof2isinlist[1]andsoforth.

WhatisthelistLength?
a. listLength=10.

WhatisthesearchItem?
a. searchItem=4.

Whatisthefirst?
a. 0

Whatisthelast?
a. ListLength1=101=9

Whatisthemiddle?
a. (0+9)/2=4

CSC118FUNDAMENTALSOFALGORITHMDEVELOPMENT
Chapter2:IntroductiontoProblemSolvingUsingComputer

Pseudocode
Problem:Searchpage(list[],listLength,searchItem)
found=FALSE
list[]={1,2,3,4,5,6,7,8,9,10}
listLength=10
searchItem=4
first=0
last=listLength1
1.Start
2.DOWHILEfirst<=lastandfoundisFALSE

middle=(first+last)/2

IFlist[middle]==searchItem

setfound=TRUE

ELSEIFlist[middle]>searchItem

last=middle1

ELSE

first=middle+1

ENDIF
ENDDO
3.IFfoundisTRUE

returnandreportthemiddle
ELSEreturn1
ENDIF
4.Stop

Iterationofbinarysearch
Iteration first last middle list[middle] Found
1
0
9
4
5
FALSE
2
0
3
1
2
FALSE
3
2
3
2
3
FALSE
4
3
3
3
4
TRUE

CSC118FUNDAMENTALSOFALGORITHMDEVELOPMENT
Chapter2:IntroductiontoProblemSolvingUsingComputer

J.

BubbleSort

Pseudocode

BubbleSort(list[],listLength)
iteration1
index0

1.Start
2.DOWHILEiteration<listLength
DOWHILEindex<listLengthiteration
IFlist[index]<list[j+1]
temp=list[index]
[index]=list[index+1]
list[j+1]=temp
ENDIF
ENDDO
ENDDO
3.Stop

Iteration
Tableofiteration

Execution

Iteration Index List[0] List[1] List[2] List[3]


1

0
1
2
0
1
2
0
1
2

2
2
2
2
2
2
1
1
1

3
3
3
3
1
1
2
2
2

5
5
1
1
3
3
3
3
3

1
1
5
5
5
5
5
5
5

Temp
3
NoExecution
5
NoExecution
3
NoExecution
2
NoExecution
NoExecution

Originallist:3251

Iteration1
temp=3
list[0]=2
list[1]=3
temp=5
list[2]=1
list[3]=5
list[0]=2
list[1]=3
list[2]=1
list[3]=5

Iteration2
temp=3
list[1]=1
list[2]=3
list[0]=2
list[1]=1
list[2]=3
list[3]=5

Iteration3
temp=2
list[0]=1
list[1]=2
list[0]=1
list[1]=2
list[2]=3
list[3]=5

SortedList:1235

You might also like