C++PlusDataStructures,
ThirdEdition
byNellDale ISBN:0763704814
JonesandBartlettPublishers
©2003(816pages)
Thisbookfocusesonabstract
datatypesasviewedfrom
threedifferentperspectives:
theirspecification,their
application,andtheir
implementation.
TableofContents
C++PlusDataStructures,Third
Edition
Preface
SoftwareEngineering
Chapter1 Principles
DataDesignand
Chapter2 Implementation
ADTsUnsortedListand
Chapter3 SortedList
Chapter4 - ADTsStackandQueue
Chapter5 - LinkedStructures
Chapter6 - ListsPlus
Programmingwith
Chapter7 Recursion
Chapter8
- BinarySearchTrees
PriorityQueues,Heaps,
Chapter9 Graphs,andSets
SortingandSearching
Chapter10 Algorithms
AnswerstoSelectedExercises
AppendixA - ReservedWords
AppendixB - OperatorPrecedence
ASelectionofStandard
AppendixC LibraryRoutines
AppendixD - CharacterSets
TheStandardTemplate
AppendixE Library
Glossary
Index
ListofFigures
ListofTables
ListofC++Examples
ListofSidebars
BackCover
C++PlusDataStructuresisdesignedforacoursein
DataStructureswhereC++istheprogramming
language.Thebookfocusesonabstractdatatypesas
viewedfromthreedifferentperspectives:their
specification,theirapplication,andtheir
implementation.Theauthorsstresscomputerscience
theoryandsoftwareengineeringprinciples,including
modularization,dataencapsulation,informationhiding,
dataabstraction,object-orienteddecomposition,
functionaldecomposition,theanalysisofalgorithms,
andlife-cyclesoftwareverificationmethods.Finally,
throughclassicDalepedagogystudentsareoffereda
clear,easy-to-understanddiscussionofimportant
theoreticalconstructsandtheirimplementationin
C++.
C++PlusDataStructures,ThirdEdition
NellDaleUniversityofTexas,
Austin
JONESANDBARTLETTPUBLISHERS
Sudbury,MassachusettsBOSTONTORONTOLONDONSINGAPORE
WorldHeadquarters
JonesandBartlettPublishers
40TallPineDrive
Sudbury,MA01776
978-443-5000
<>
www.jbpub.com
JonesandBartlettPublishersCanada
2406NikannaRoad
Mississauga,ONL5C2W6
CANADA
JonesandBartlettPublishersInternational
BarbHouse,BarbMews
LondonW67PA
UK
Copyright©2003byJonesandBartlettPublishers,Inc.
Coverimage©DouglasE.Walker/Masterfile
Allrightsreserved.Nopartofthematerialprotectedbythiscopyright
noticemaybereproducedorutilizedinanyform,electronicor
mechanical,includingphotocopying,recording,oranyinformation
storageorretrievalsystem,withoutwrittenpermissionfromthecopyright
owner.
ChiefExecutiveOfficer:ClaytonJones
ChiefOperatingOfficer:DonW.Jones,Jr.
ExecutiveV.P.andPublisher:RobertHolland
V.P.,DesignandProduction:AnneSpencer
V.P.,ManufacturingandInventoryControl:ThereseBräuer
Editor-in-Chief,College:J.MichaelStranz
ProductionManager:AmyRose
MarketingManager:NathanSchultz
AssociateProductionEditor:KarenFerreira
EditorialAssistant:TheresaDiDonato
ProductionAssistant:JennyMclsaac
CoverDesign:Night&DayDesign
Composition:NortheastCompositors,Inc.
TextDesign:AnneSpencer
PrintingandBinding:CourierWestford
CoverPrinting:LehighPress
LibraryofCongressCataloging-in-PublicationData
Dale,NellB.
C++plusdatastructures/NellDale.-3rded.
p.cm.
ISBN0-7637-0481-4
1.C++(Computerprogramlanguage)2.Datastructures(Computer
science)I.Title.
QA76.73.C153D3342003
005.7'3-dc21
2002034168
ThisbookwastypesetinQuark4.1onaMacintoshG4.Thefontfamilies
usedwereRotisSansSerif,RotisSerif,andPrestigeElite.Thefirst
printingwasprintedon45#HighlandBook.
PrintedintheUnitedStatesofAmerica
060504030210987654321
ToAl,myhusbandandbestfriend,toourchildrenandourchildren's
children,andtoourdogsMaggieandChrissie,whoroundoutourfamily.
N.D.
Preface
Historically,acourseondatastructureshasbeenamainstayofmost
computersciencedepartments.Overthelast18years,however,the
focusofthiscoursehasbroadenedconsiderably.Thetopicofdata
structureshasnowbeensubsumedunderthebroadertopicofabstract
datatypes(ADTs)-thestudyofclassesofobjectswhoselogicalbehavior
isdefinedbyasetofvaluesandasetofoperations.
Thetermabstractdatatypedescribesacomprehensivecollectionofdata
valuesandoperations;thetermdatastructuresreferstothestudyofdata
andhowtorepresentdataobjectswithinaprogram;thatis,the
implementationofstructuredrelationships.Theshiftinemphasisis
representativeofthemovetowardsmoreabstractionincomputerscience
education.Wenowareinterestedinthestudyoftheabstractproperties
ofclassesofdataobjectsinadditiontohowtheobjectsmightbe
representedinaprogram.JohannesJ.Martinputitsuccinctly:"...
dependingonthepointofview,adataobjectischaracterizedbyitstype
(fortheuser)orbyitsstructure(fortheimplementor)."[1]
ThreeLevelsofAbstraction
Thefocusofthisbookisonabstractdatatypesasviewedfromthree
differentperspectives:theirspecification,theirapplication,andtheir
implementation.Thespecificationperspectivedescribesthelogicalor
abstractlevelofdatatypes,andisconcernedwithwhattheoperations
do.Theapplicationlevel,sometimescalledtheuserlevel,isconcerned
withhowthedatatypemightbeusedtosolveaproblem,andisfocused
onwhytheoperationsdowhattheydo.Theimplementationlevelis
wheretheoperationsareactuallycoded.Thislevelisconcernedwiththe
howquestions.
Withinthisfocus,westresscomputersciencetheoryandsoftware
engineeringprinciples,includingmodularization,dataencapsulation,
informationhiding,dataabstraction,object-orienteddecomposition,
functionaldecomposition,theanalysisofalgorithms,andlife-cycle
softwareverificationmethods.Wefeelstronglythattheseprinciples
shouldbeintroducedtocomputersciencestudentsearlyintheir
educationsothattheylearntopracticegoodsoftwaretechniquesfrom
thebeginning.
Anunderstandingoftheoreticalconceptshelpsstudentsputthenew
ideastheyencounterintoplace,andpracticaladviceallowsthemto
applywhattheyhavelearned.Toteachtheseconceptstostudentswho
maynothavecompletedmanycollege-levelmathematicscourses,we
consistentlyuseintuitiveexplanations,evenfortopicsthathaveabasis
inmathematics,liketheanalysisofalgorithms.Inallcases,ourhighest
goalhasbeentomakeourexplanationsasreadableandaseasily
understandableaspossible.
[1]JohannesJ.Martin,DataTypesandDataStructures,Prentice-Hall
InternationalSeriesinComputerScience,C.A.R.Hoare,SeriesEditor,
Prentice-HallInternational,(UK),LTD,1986,p.1.
PrerequisiteAssumptions
Inthisbook,weassumethatstudentsarefamiliarwiththefollowingC++
constructs:
Built-insimpledatatypes
StreamI/Oasprovidedin<iostream>
StreamI/Oasprovidedin<fstream>
Controlstructureswhile,do-while,for,if,andswitch
User-definedfunctionswithvalueandreferenceparameters
Built-inarraytypes
Classconstruct
Wehaveincludedsidebarswithinthetexttorefreshstudents'memory
concerningsomeofthedetailsofthesetopics.
ChangesintheThirdEdition
Thethirdeditionincorporatesthefollowingchanges:
Object-orientedconstructsmovedforward:Inthelastfiveyears,objectorientedprogramminghasbecomepartofthefirst-yearcurriculum,as
demonstratedbyitsinclusioninallvariationsofthefirstyearoutlinedin
theComputingCurricula2001developedbytheJointTaskForceofthe
IEEEComputerSocietyandtheAssociationforComputingMachinery.
Accordingly,theclassconcepthasmovedintothefirstsemester.
Becauseofthis,weassumethatstudentshavehadexperienceusing
classes,andwethereforemovedmuchofthediscussionofhowtodefine
andaccessclassestoasidebar.Wehavekeptasmalldiscussioninthe
maintext.Manystudentshavealreadyseeninheritanceand
polymorphism,buttheconceptsaretooimportanttomovetoasidebar,
sowehavemovedthemfromChapter6toChapter2.
Moreemphasisonobject-orienteddesign:Object-orienteddesignisa
hardtopicformoststudents,becausepeopleusuallythinkprocedurallyin
theirlives.Becauseofthis,weintroduceamethodologywithfourphases:
brainstorming,duringwhichthepossibleobjectsinaproblemare
isolated;filtering,duringwhichthesetofpossibleobjectsarereexamined
tolookforduplicatesand/ormissingobjects;scenarios,duringwhich
handsimulationsoftheprocessingtakeplaceasking"whatif"questions
andassigningresponsibilitiestoclasses;andresponsibilityalgorithms,
duringwhichthealgorithmsfortheclassesaredesigned.WeuseCRC
cardstocapturetheresultsofthefour-phaseprocess.Theoutputfrom
thescenariosphaseisaCRCcardforeachclass.TheCRCcardliststhe
responsibilitiesoftheclassandanyotherclasseswithwhichtheclass
mustcollaborate,hencethenameCRC:class,responsibility,
collaboration.
Morepracticalemphasisontesting:Theconceptofamultipurposetest
driverisintroducedinChapter1.Afteratestplanhasbeendesigned,itis
implementedasinputtothetestdriver.Throughouttherestofthebook,
thistechniqueisusedtotesttheADTs.Thedrivers,theinputdata,and
theoutputdataareavailableonthebook'swebsite:
/>Reduceduseoftemplates:Theconceptofgenericdatatypes,as
implementedinC++usingtemplates,isveryimportant.Makingevery
ADTaclasstemplateaftertemplatesareintroducedinChapter4,
however,insertsanunnecessarycomplexityintoalreadycomplexcode.
Thus,whenintroducinganewconstructsuchasalinkedlistorabinary
searchtree,wehavechosentouseclassesratherthanclasstemplates.
Subsequentimplementationsofaconstructareoftenintheformofclass
templates,orthestudentisaskedtotransformaclassintoaclass
templateintheexercises.
Nonlinkedbinarytreerepresentationcoveredwithbinarytrees:The
nonlinkedrepresentationofabinarytreeisanimportantconceptwithin
itsownright,notjustasanimplementationforaheap.This
implementation,therefore,iscoveredinChapter8withothertree
implementationtechniques.
Removalofmaterialonbinaryexpressiontrees:Althoughinteresting
applicationsoftrees,binaryexpressiontreesdonotfitintothediscussion
ofabstractdatatypes.Thus,wehavemovedthisdiscussiontotheweb
site.
InclusionoftheADTset:TheexclusionoftheADTsethasbeenan
omissionfrompreviouseditions.Notonlyisasetaninteresting
mathematicalobject,butthereareinterestingimplementationissues.We
proposetwoimplementations,oneexplicit(bitvector)andoneimplicit
(list-based).
ContentandOrganization
Chapter1outlinesthebasicgoalsofhigh-qualitysoftware,andthebasic
principlesofsoftwareengineeringfordesigningandimplementing
programstomeetthesegoals.Abstraction,functionaldecomposition,
andobject-orienteddesignarediscussed.Thischapteralsoaddresses
whatweseeasacriticalneedinsoftwareeducation:theabilitytodesign
andimplementcorrectprogramsandtoverifythattheyareactually
correct.Topicscoveredincludetheconceptof"life-cycle"verification;
designingforcorrectnessusingpreconditionsandpostconditions;theuse
ofdeskcheckinganddesign/codewalkthroughsandinspectionsto
identifyerrorsbeforetesting;debuggingtechniques,datacoverage
(black-box),andcodecoverage(clear-orwhite-box)approaches;test
plans,unittesting,andstructuredintegrationtestingusingstubsand
drivers.Theconceptofageneralizedtestdriverispresentedand
executedinaCaseStudythatdevelopstheADTFraction.
Chapter2presentsdataabstractionandencapsulation,thesoftware
engineeringconceptsthatrelatetothedesignofthedatastructuresused
inprograms.Threeperspectivesofdataarediscussed:abstraction,
implementation,andapplication.Theseperspectivesareillustratedusing
areal-worldexample,andthenareappliedtobuilt-indatastructuresthat
C++supports:structsandarrays.TheC++classtypeispresentedasthe
waytorepresenttheabstractdatatypesweexamineinsubsequent
chapters.Theprinciplesofobject-orientedprogramming-encapsulation,
inheritance,andpolymorphism-areintroducedherealongwiththe
accompanyingC++implementationconstructs.TheCaseStudyatthe
endofthischapterreinforcestheideasofdataabstractionand
encapsulationindesigningandimplementingauser-defineddatatypefor
generalizedstringinputandoutput.Thisclassistestedusingaversionof
thegeneralizedtestdriver.
Chapter2endswithadiscussionoftwoC++constructsthathelpusers
writebettersoftware:namespaceandexceptionhandlingusingthe
try/catchstatement.Variousapproachestoerrorhandlingare
demonstratedinsubsequentchapters.
WewouldliketothinkthatthematerialinChapters1and2isareview
formoststudents.Theconceptsinthesetwochapters,however,areso
crucialtothefutureofanyandallstudentsthatwefeelthatwecannot
relyontheassumptionthattheyhaveseenthematerialbefore.
Chapter3introducesthemostfundamentalabstractdatatypeofall:the
list.Thechapterbeginswithageneraldiscussionofoperationson
abstractdatatypesandthenpresentstheframeworkwithwhichallofthe
otherdatatypesareexamined:apresentationanddiscussionofthe
specification,abriefapplicationusingtheoperations,andthedesignand
codingoftheoperations.Boththeunsortedandthesortedlistsare
presentedwithanarray-basedimplementation.Overloadingtherelational
operatorsispresentedasawaytomaketheimplementationsmore
generic.Thebinarysearchisintroducedasawaytoimprovethe
performanceofthesearchoperationinthesortedlist.Becausethereis
morethanonewaytosolveaproblem,wediscusshowcompeting
solutionscanbecomparedthroughtheanalysisofalgorithms,usingBigOnotation.Thisnotationisthenusedtocomparetheoperationsinthe
unsortedlistandthesortedlist.Thefour-phaseobject-oriented
methodologyispresentedanddemonstratedintheCaseStudybyusing
asimplerealestatedatabase.
Chapter4introducesthestackandthequeuedatatypes.Eachdatatype
isfirstconsideredfromitsabstractperspective,andtheideaofrecording
thelogicalabstractioninanADTspecificationisstressed.Thenthesetof
operationsisimplementedinC++usinganarray-basedimplementation.
Theconceptofdynamicallocationisintroduced,alongwiththesyntaxfor
usingC++pointervariables,andthenusedtodemonstratehowarrays
canbedynamicallyallocatedtogivetheusermoreflexibility.Withthe
introductionofdynamicstorage,thedestructormustbeintroduced.
Templatesareintroducedasawayofimplementinggenericclasses.A
CaseStudyusingstacks(postfixexpressionevaluator)andoneusing
queues(simulation)arepresented.
Chapter5reimplementstheADTsfromChapters3and4aslinked
structures.Thetechniqueusedtolinktheelementsindynamically
allocatedstorageisdescribedindetailandillustratedwithfigures.The
array-basedimplementationsandthelinkedimplementationsarethen
comparedusingBig-Onotation.
Chapter6isacollectionofadvancedconceptsandtechniques.Circular
linkedlistsanddoublylinkedlistsarediscussed.Theinsertion,deletion,
andlisttraversalalgorithmsaredevelopedandimplementedforeach
variation.Analternativerepresentationofalinkedstructure,usingstatic
allocation(anarrayofstructs),isdesigned.Classcopyconstructors,
assignmentoverloading,anddynamicbindingarecoveredindetail.The
CaseStudyusesdoublylinkedliststoimplementlargeintegers.
Chapter7discussesrecursion,givingthestudentanintuitive
understandingoftheconcept,andthenshowshowrecursioncanbe
usedtosolveprogrammingproblems.Guidelinesforwritingrecursive
functionsareillustratedwithmanyexamples.Afterdemonstratingthata
by-handsimulationofarecursiveroutinecanbeverytedious,asimple
three-questiontechniqueisintroducedforverifyingthecorrectnessof
recursivefunctions.Becausemanystudentsarewaryofrecursion,the
introductiontothismaterialisdeliberatelyintuitiveandnonmathematical.
Amoredetaileddiscussionofhowrecursionworksleadstoan
understandingofhowrecursioncanbereplacedwithiterationand
stacks.TheCaseStudydevelopsandimplementstheQuick-Sort
algorithm.
Chapter8introducesbinarysearchtreesasawaytoarrangedata,giving
theflexibilityofalinkedstructurewithO(log2N)insertionanddeletion
time.Inordertobuildonthepreviouschapterandexploittheinherent
recursivenatureofbinarytrees,thealgorithmsfirstarepresented
recursively.Afteralltheoperationshavebeenimplementedrecursively,
wecodetheinsertionanddeletionoperationsiterativelytoshowthe
flexibilityofbinarysearchtrees.Anonlinkedarray-basedbinarytree
implementationisdescribed.TheCaseStudydiscussestheprocessof
buildinganindexforamanuscriptandimplementsthefirstphase.
Chapter9presentsacollectionofotherbranchingstructures:priority
queues(implementedwithbothlistsandheaps),graphs,andsets.The
graphalgorithmsmakeuseofstacks,queues,andpriorityqueues,thus
bothreinforcingearliermaterialanddemonstratinghowgeneralthese
structuresare.Twosetimplementationsarediscussed:thebit-vector
representation,inwhicheachiteminthebasesetisassigneda
present/absentflagandtheoperationsarethebuilt-inlogicoperations,
andalist-basedrepresentation,inwhicheachiteminasetis
representedinalistofsetitems.Iftheitemisnotinthelist,itisnotinthe
set.
Chapter10presentsanumberofsortingandsearchingalgorithmsand
asksthequestion:Whicharebetter?Thesortingalgorithmsthatare
illustrated,implemented,andcomparedincludestraightselectionsort,
twoversionsofbubblesort,quicksort,heapsort,andmergesort.The
sortingalgorithmsarecomparedusingBig-Onotation.Thediscussionof
algorithmanalysiscontinuesinthecontextofsearching.Previously
presentedsearchingalgorithmsarereviewedandnewonesare
described.Hashingtechniquesarediscussedinsomedetail.Finally,
radixsortispresentedandanalyzed.
AdditionalFeatures
ChapterGoalsAsetofgoalspresentedatthebeginningofeachchapter
helpsthestudentsassesswhattheywilllearn.Thesegoalsaretestedin
theexercisesattheendofeachchapter.
ChapterExercisesMostchaptershavemorethan35exercises.They
varyinlevelsofdifficulty,includingshortprogrammingproblems,the
analysisofalgorithms,andproblemstotestthestudent'sunderstanding
ofconcepts.Approximatelyone-thirdoftheexercisesareansweredin
thebackofthebook.Theanswerkeyfortheremainingexercisesisin
theInstructor'sGuide.
CaseStudiesTherearesevencasestudies.Eachincludesaproblem
description,ananalysisoftheprobleminputandrequiredoutput,anda
discussionoftheappropriatedatatypestouse.Severalofthecase
studiesarecompletelycodedandtested.Othersareleftatvarious
stagesintheirdevelopment,requiringthestudenttocompleteandtest
thefinalversion.
ProgramDiskThespecificationandimplementationofeachclass
representinganADTisavailableonaprogramdiskthatcanbe
downloaded,freeofcharge,fromtheJonesandBartlettStudentDiskette
PageontheWorldWideWeb(www.jbpub.com/disks).Thesource
codeforthecompletedcasestudiesandthepartialsourcecodeforthe
othersisalsoavailable.
InstructorSupportMaterialInstructorteachingtoolsandresourcesare
availableonthewebat
Onthissite
youwillfind:
Goals
Outlines
TeachingNotes:suggestionsforhowtoteachthematerial
coveredineachchapter
Workouts:suggestionsforin-classactivities,discussion
questions,andshortexercises
ExerciseKey:answerstothosequestionsthatarenotsolvedin
thebackofthebook
ProgrammingAssignments:acollectionofawiderangeof
assignmentscarefullychosentoillustratethetechniques
describedinthetext
ElectronicTestBank:thiscomputerizedTestBankallowsyouto
createcustomizedexamsorquizzesfromacollectionofpremadequestionssortedbychapter.Updatedforthisedition,the
TestBankquestionscanbeeditedandsupplemented,and
answersareprovidedforallpre-madequestions.Eachtestis
developedusingBrownstoneDiplomaSoftwareandisavailable
onthebook'swebsite.
PowerPointPresentations:newPowerPointslidesdeveloped
specificallyforthethirdeditionprovideanexcellentvisual
accompanimenttolectures.ThePowerPointpresentationsfor
eachchapteraredesignedtocoordinatewiththematerialinthe
textbook,andcanbedownloadedfromthebook'swebsite.
Acknowledgments
Wewouldliketothankthefollowingpeoplewhotookthetimetoreview
thefirsteditionofthismanuscript:DonaldBagert,TexasTechUniversity;
SusanGauch,UniversityofKansas;PamelaLawhead,Universityof
Mississippi;PatNettnin,FingerLakesCommunityCollege;Bobbie
Othmer,WestminsterCollegeofSaltLakeCity;SuzannePawlan-Levy,
AllanHancockCollege;CarolRoberts,UniversityofMaine;andRobert
Strader,StephenF.AustinStateUniversity.Thanksalsotoallofyouwho
tookthetimetoanswerourelectronicsurveyconcerningthisthird
edition.
AspecialthankstoJohnMcCormick,UniversityofNorthernIowa,Mark
Headington,UniversityofWisconsin-LaCrosse,andDanJoyce.Johnand
DangraciouslyallowedustousesomeoftheiranalogiesfromAdaPlus
DataStructuresandObject-OrientedDataStructuresUsingJava,
respectively.Mark'sideas,suggestions,andsharpeyeswereinvaluable.
ThanksalsotothestudentsatUppsalaUniversityinSwedenwhoused
thefinaldraftofthemanuscriptofthesecondeditioninacourseinthe
fallof1997.Becausenon-Englishreadersseewhatiswritten,notwhat
theyexpecttosee,theircommentswereinvaluableincleaningup
ambiguouswording.
ThankstomyhusbandAl,ourchildrenandgrandchildrentoonumerous
toname,andourdogs,Maggie,whokeepsmyfeetwarm,andChrissie,
whoseroleinlifeistokeepthehouseinturmoilandmud.
Avirtualbouquetofrosestothepeoplewhohaveworkedonthisbook:
MikeandSigridWile,alongwithourJonesandBartlettfamily.Theresa
DiDonato,ajack-of-all-tradeswhohelpedwiththesurvey;Jenny
Mclsaac,whojumpeddirectlyintothefryingpanonherfirstday;Nathan
Schultz,whose"cando"attitudeisajoytoworkwith;andMichaelStranz
andAmyRose,whoseteameffortsustainsallofus.Amy,thankheavens
thisproductionschedulewasalittlemoreleisurelythanthelast-butnot
bymuch!
N.D.
Chapter1:SoftwareEngineeringPrinciples
Goals
Afterstudyingthischapter,youshouldbeableto
Describethegeneralactivitiesinthesoftwarelifecycle
Describethegoalsfor"quality"software
Explainthefollowingterms:softwarerequirements,software
specifications,algorithm,informationhiding,abstraction,stepwise
refinement
Explainandapplythefundamentalideasoftop-downdesign
Explainandapplythefundamentalideasofobject-oriented
design
Identifyseveralsourcesofprogramerrors
Describestrategiestoavoidsoftwareerrors
Specifythepreconditionsandpostconditionsofaprogram
segmentorfunction
Showhowdeskchecking,codewalk-throughs,anddesignand
codeinspectionscanimprovesoftwarequalityandreducethe
softwaredevelopmenteffort
Explainthefollowingterms:acceptancetests,regressiontesting,
verification,validation,functionaldomain,black-boxtesting,
white-boxtesting
Stateseveraltestinggoalsandindicatewheneachwouldbe
appropriate
Describeseveralintegration-testingstrategiesandindicatewhen
eachwouldbeappropriate
Explainhowprogramverificationtechniquescanbeapplied
throughoutthesoftwaredevelopmentprocess
CreateaC++testdriverprogramtotestasimpleclass
Atthispointinyourcomputingcareer,youhavecompletedatleastone
semesterofcomputersciencecoursework.Youcantakeaproblemof
mediumcomplexity,writeanalgorithmtosolvetheproblem,codethe
algorithminC++,anddemonstratethecorrectnessofyoursolution.At
least,that'swhatthesyllabusforyourintroductoryclasssaidyoushould
beabletodowhenyoucompletethecourse.Nowthatyouarestarting
yoursecond(orthird?)semester,itistimetostopandreviewthose
principlesthat,ifadheredto,guaranteethatyoucanindeeddowhatyour
previoussyllabusclaimed.
Inthischapter,wereviewthesoftwaredesignprocessandthe
verificationofsoftwarecorrectness.InChapter2,wereviewdatadesign
andimplementation.
1.1TheSoftwareProcess
Whenweconsidercomputerprogramming,weimmediatelythinkof
writingaprogramforacomputertoexecute-thegenerationofcodein
somecomputerlanguage.Asabeginningstudentofcomputerscience,
youwroteprogramsthatsolvedrelativelysimpleproblems.Muchofyour
initialeffortwentintolearningthesyntaxofaprogramminglanguage
suchasC++:thelanguage'sreservedwords,itsdatatypes,its
constructsforselection(if-elseandswitch)andlooping(while,do
while,andfor),anditsinput/outputmechanisms(cinandcout).
Youmayhavelearnedaprogrammingmethodologythattookyoufrom
theproblemdescriptionthatyourinstructorhandedoutalltheway
throughthedeliveryofagoodsoftwaresolution.Programmershave
createdmanydesigntechniques,codingstandards,andtestingmethods
tohelpdevelophigh-qualitysoftware.Butwhybotherwithallthat
methodology?Whynotjustsitdownatacomputerandwriteprograms?
Aren'twewastingalotoftimeandeffort,whenwecouldjustgetstarted
onthe"real"job?
Ifthedegreeofourprogrammingsophisticationneverhadtoriseabove
theleveloftrivialprograms(likesummingalistofpricesoraveraging
grades),wemightgetawaywithsuchacode-firsttechnique(or,rather,
lackoftechnique).Somenewprogrammersworkthisway,hackingaway
atthecodeuntiltheprogramworksmoreorlesscorrectly-usuallyless.
Asyourprogramsgrowlargerandmorecomplex,however,youmustpay
attentiontoothersoftwareissuesinadditiontocoding.Ifyoubecomea
softwareprofessional,somedayyoumayworkaspartofateamthat
developsasystemcontainingtensofthousands,orevenmillions,oflines
ofcode.Theactivitiesinvolvedinsuchasoftwareproject'swhole"life
cycle"clearlygobeyondjustsittingdownatacomputerandwriting
programs.Theseactivitiesinclude
ProblemanalysisUnderstandingthenatureoftheproblemtobe
solved
RequirementselicitationDeterminingexactlywhattheprogram
mustdo
RequirementsdefinitionSpecifyingwhattheprogrammustdo
(functionalrequirements)andanyconstraintsonthesolution
approach(nonfunctionalrequirementssuchaswhatlanguageto
use)
High-andlow-leveldesignRecordinghowtheprogrammeetsthe
requirements,fromthe"bigpicture"overviewtothedetailed
design
ImplementationofthedesignCodingaprograminacomputer
language
TestingandverificationDetectingandfixingerrorsand
demonstratingthecorrectnessoftheprogram
DeliveryTurningoverthetestedprogramtothecustomeroruser
(orinstructor!)
OperationActuallyusingtheprogram
MaintenanceMakingchangestofixoperationalerrorsandtoadd
ormodifytheprogram'sfunction
Softwaredevelopmentisnotsimplyamatterofgoingthroughthese
stepssequentially.Rather,manyactivitiestakeplaceconcurrently.We
maycodeonepartofthesolutionwhilewedesignanotherpart,ordefine
requirementsforanewversionofaprogramwhilewecontinuetesting
thecurrentversion.Oftenanumberofpeoplemayworkondifferentparts
ofthesameprogramsimultaneously.Keepingtrackofalltheseactivities
isnotaneasytask.
Weusethetermsoftwareengineeringtorefertothedisciplineconcerned
withallaspectsofthedevelopmentofhighqualitysoftwaresystems.It
encompassesallvariationsoftechniquesusedduringthesoftwarelife
cycleplussupportingactivitiessuchasdocumentationandteamwork.A
softwareprocessisaspecificsetofinterrelatedsoftwareengineering
techniques,usedbyapersonororganizationtocreateasystem.
SoftwareengineeringThedisciplinedevotedtothedesign,
production,andmaintenanceofcomputerprogramsthatare
developedontimeandwithincostestimates,usingtoolsthathelpto
managethesizeandcomplexityoftheresultingsoftwareproducts
SoftwareprocessAstandard,integratedsetofsoftware
engineeringtoolsandtechniquesusedonaprojectorbyan
organization
Whatmakesourjobsasprogrammersorsoftwareengineerschallenging
isthetendencyofsoftwaretogrowinsizeandcomplexityandtochange
ateverystageofitsdevelopment.Agoodsoftwareprocessusestoolsto
managethissizeandcomplexityeffectively.Usuallyaprogrammertakes
advantageofseveraltoolboxes,eachcontainingtoolsthathelptobuild
andshapeasoftwareproduct.
HardwareOnetoolboxcontainsthehardwareitself:thecomputersand
theirperipheraldevices(suchasmonitors,terminals,storagedevices,
andprinters),onwhichandforwhichwedevelopsoftware.
SoftwareAsecondtoolboxcontainsvarioussoftwaretools:operating
systemstocontrolthecomputer'sresources,texteditorstohelpusenter
programs,compilerstotranslatehigh-levellanguageslikeC++into
somethingthatthecomputercanexecute,interactivedebugging
programs,test-datagenerators,andsoon.You'veusedsomeofthese
toolsalready.
IdeawareAthirdtoolboxisfilledwiththesharedbodyofknowledgethat
programmershavecollectedovertime.Thisboxcontainsthealgorithms
thatweusetosolvecommonprogrammingproblemsaswellasdata
structuresformodelingtheinformationprocessedbyourprograms.
Recallthatanalgorithmisastep-by-stepdescriptionofthesolutiontoa
problem.Howwechoosebetweentwoalgorithmsthatcarryoutthesame
taskoftendependsontherequirementsofaparticularapplication.Ifno
relevantrequirementsexist,thechoicemaybebasedonthe
programmer'sownstyle.