Tải bản đầy đủ (.pdf) (993 trang)

Data structures and algorithms in java peter drake

Bạn đang xem bản rút gọn của tài liệu. Xem và tải ngay bản đầy đủ của tài liệu tại đây (8.52 MB, 993 trang )




Tableof

Contents
• Index

DataStructuresandAlgorithmsinJava
ByPeterDrake
Publisher :PrenticeHall
PubDate :December19,2005
PrintISBN-10 :0-13-146914-2
PrintISBN-13 :978-0-13-146914-3
eTextISBN-10 :0-13-174690-1
eTextISBN-13 :978-0-13-174690-9
Pages :592


Anabundanceofunique,interestingexamples,useoftheUnified
ModelingLanguagethroughout,andthenewestJava1.5features
characterizethistext.Drakeprovidesaconciseandengaging
introductiontoJavaandobject-orientedprogramming,assuming
familiaritywiththebasiccontrolstructuresofJavaorCandonly
apre-calculuslevelofmathematics.




DataStructuresandAlgorithmsinJava
ByPeterDrake


Publisher :PrenticeHall
PubDate :December19,2005
PrintISBN-10 :0-13-146914-2

PrintISBN-13 :978-0-13-146914-3
Tableof eTextISBN-10 :0-13-174690-1

Contents eTextISBN-13 :978-0-13-174690-9
• Index
Pages :592














































Copyright
Preface
IntendedAudience
PartI:Object-OrientedProgramming
Chapter1.Encapsulation

Section1.1.SoftwareDevelopment
Section1.2.ClassesandObjects
Section1.3.UsingObjects
Summary
Vocabulary
Problems
Projects
Chapter2.Polymorphism
Section2.1.ReferenceTypes
Section2.2.Arrays
Section2.3.Interfaces
Section2.4.Overloading
Summary
Vocabulary
Problems
Projects
Chapter3.Inheritance

xi
xi
1
3
3
9
18
32
32
34
35
37

37
44
55
59
61
61
62
62
67















































































Section3.1.ExtendingaClass
Section3.2.TheObjectClass
Section3.3.PackagesandAccessLevels
Summary

Vocabulary
Problems
Projects
PartII:LinearStructures
Chapter4.StacksandQueues
Section4.1.TheStackInterface
Section4.2.TheCallStack
Section4.3.Exceptions
Section4.4.TheQueueInterface
Summary
Vocabulary
Problems
Projects
Chapter5.Array-BasedStructures
Section5.1.ShrinkingandStretchingArrays
Section5.2.ImplementingStacksandQueues
Section5.3.TheListInterface
Section5.4.Iterators
Section5.5.TheJavaCollectionsFramework:AFirstLook
Summary
Vocabulary
Problems
Projects
Chapter6.LinkedStructures
Section6.1.ListNodes
Section6.2.StacksandQueues
Section6.3.TheLinkedListClass
Section6.4.TheJavaCollectionsFrameworkRevisited
Summary
Vocabulary

Problems
Projects
PartIII:Algorithms
Chapter7.AnalysisofAlgorithms

67
77
79
82
83
84
84
85
87
87
97
100
108
114
114
115
116
119
119
127
133
139
151
153
154

154
155
157
157
161
168
176
178
178
179
179
181
183




Section7.1.Timing

183



Section7.2.AsymptoticNotation

186













































































Section7.3.CountingSteps
Section7.4.Best,Worst,andAverageCase
Section7.5.AmortizedAnalysis
Summary
Vocabulary
Problems
Projects
Chapter8.SearchingandSorting
Section8.1.LinearSearch
Section8.2.BinarySearch
Section8.3.InsertionSort
Section8.4.TheComparableInterface
Section8.5.SortingLinkedLists
Summary
Vocabulary
Problems
Projects
Chapter9.Recursion
Section9.1.ThinkingRecursively
Section9.2.AnalyzingRecursiveAlgorithms

Section9.3.MergeSort
Section9.4.Quicksort
Section9.5.AvoidingRecursion
Summary
Vocabulary
Problems
Projects
PartIV:TreesandSets
Chapter10.Trees
Section10.1.BinaryTrees
Section10.2.TreeTraversal
Section10.3.GeneralTrees
Summary
Vocabulary
Problems
Projects

192
197
199
202
202
203
203
205
206
207
211
214
218

219
221
221
221
223
223
231
235
239
244
248
249
250
251
253
255
255
265
270
280
280
281
282















































































Chapter11.Sets
Section11.1.TheSetInterface
Section11.2.OrderedLists

283
283
291

Section11.3.BinarySearchTrees
296
Section11.4.HashTables
305
Section11.5.TheJavaCollectionsFrameworkAgain
316
Summary
318
Vocabulary
319
Problems
320
Projects

321
PartV:AdvancedTopics
323
Chapter12.AdvancedLinearStructures
325
Section12.1.BitVectors
325
Section12.2.SparseArrays
335
Section12.3.ContiguousRepresentationofMultidimensionalArrays 337
Section12.4.AdvancedSearchingandSorting
343
Summary
347
Vocabulary
348
Problems
348
Projects
349
Chapter13.Strings
351
Section13.1.StringsandStringBuilders
351
Section13.2.StringMatching
355
Summary
366
Vocabulary
367

Problems
367
Projects
368
Chapter14.AdvancedTrees
369
Section14.1.Heaps
369
Section14.2.DisjointSetClusters
377
Section14.3.DigitalSearchTrees
383
Section14.4.Red-BlackTrees
389
Summary
404
Vocabulary
405
Problems
406
Projects
406
Chapter15.Graphs
407
Section15.1.Terminology
408





Section15.2.Representation

413



Section15.3.GraphTraversal

419




Section15.4.TopologicalSorting
Section15.5.ShortestPaths

422
427






































































Section15.6.MinimumSpanningTrees
Summary
Vocabulary
Problems

Projects
Chapter16.MemoryManagement
Section16.1.ExplicitMemoryManagement
Section16.2.AutomaticMemoryManagement
Summary
Vocabulary
Problems
Projects
Chapter17.OuttotheDisk
Section17.1.InteractingwithFiles
Section17.2.Compression
Section17.3.ExternalSorting
Section17.4.B-Trees
Summary
Vocabulary
Problems
Projects
PartVI:Appendices
AppendixA.ReviewofJava
SectionA.1.TheFirstProgram
SectionA.2.VariablesandTypes
SectionA.3.Loops
SectionA.4.InteractingwiththeUser
SectionA.5.Branching
SectionA.6.MethodsandBreakingOut
SectionA.7.Constants
SectionA.8.Operators
SectionA.9.Debugging
SectionA.10.CodingConventions


432
437
437
439
439
443
443
454
463
464
465
465
467
467
477
488
494
514
514
515
515
517
519
519
521
524
526
527
529
531

533
537
538


































AppendixB.UnifiedModelingLanguage

543

SectionB.1.ClassDiagrams

543

SectionB.2.InstanceDiagrams
AppendixC.SummationFormulae
SectionC.1.SumNotation
SectionC.2.SumofConstants

547
551
551
552

SectionC.3.SumofFirstnIntegers
SectionC.4.SumsofHalvesandDoubles
SectionC.5.UpperLimitonSumofaFunction
SectionC.6.ConstantFactors
AppendixD.FurtherReading
SectionD.1.DataStructuresandAlgorithms

SectionD.2.Java
SectionD.3.Games
Index

553
554
554
555
557
557
557
558


Copyright
[Pageiv]
LibraryofCongressCataloging-in-PublicationData

Drake,Peter.
DatastructuresandalgorithmsinJava/PeterDrake.
p.cm.
Includesbibliographicalreferencesandindex.
ISBN0-13-146914-2
1.Java(Computerprogramlanguage)2.Datastructures(Computers
3.Computeralgorithms.I.Title.
QA76.73.J38D6932005
005.13'3--dc22
2005050807
VicePresidentandEditorialDirector,ECS:MarciaJ.
Horton

SeniorAcquisitionsEditor:TracyDunkelberger
AssistantEditor:CaroleSnyder
EditorialAssistant:ChristiannaLee
ExecutiveManagingEditor:VinceO'Brien
ManagingEditor:CamilleTrentacoste
ProductionEditor:DonnaCrilly


DirectorofCreativeServices:PaulBelfanti
ArtDirectorandCoverManager:JayneConte
CoverDesigner:BruceKenselaar
ManagingEditor,AVManagementandProduction:Patricia
Burns
ArtEditor:GregoryDulles
Manager,CoverVisualResearchandPermissions:Karen
Sanatar
ManufacturingManager,ESM:AlexisHeydt-Long
ManufacturingBuyer:LisaMcDowell
ExecutiveMarketingManager:RobinO'Brien
MarketingAssistant:BarrieReinhold
CoverImage:RusselIllig/Photodisc/GettyImages,Inc.
©2006,PearsonEducation,Inc.
PearsonPrenticeHall
PearsonEducation,Inc.
UpperSaddleRiver,NewJersey07458
Allrightsreserved.Nopartofthisbookmaybereproducedin
anyformorbyanymeans,withoutpermissioninwritingfrom
thepublisher.



PearsonPrenticeHall®isatrademarkofPearsonEducation,
Inc.
Theauthorandpublisherofthisbookhaveusedtheirbest
effortsinpreparingthisbook.Theseeffortsincludethe
development,research,andtestingofthetheoriesand
programstodeterminetheireffectiveness.Theauthorand
publishermakenowarrantyofanykind,expressedorimplied,
withregardtotheseprogramsorthedocumentationcontained
inthisbook.Theauthorandpublishershallnotbeliableinany
eventforincidentalorconsequentialdamagesinconnection
with,orarisingoutof,thefurnishing,performance,oruseof
theseprograms.
PrintedintheUnitedStatesofAmerica
10987654321
PearsonEducationLtd.,London
PearsonEducationAustraliaPty.Ltd.,Sydney
PearsonEducationSingapore,Pte.Ltd.
PearsonEducationNorthAsiaLtd.,HongKong
PearsonEducationCanada,Inc.,Toronto
PearsonEducacióndeMexico,S.A.deC.V.
PearsonEducationJapan,Tokyo
PearsonEducationMalaysia,Pte.Ltd.
PearsonEducation,Inc.,UpperSaddleRiver,NewJersey


[Pagexi]


Preface
IntendedAudience



[Pagexi(continued)]

IntendedAudience
Thisbookisintendedforasecondundergraduatecoursein
computerscience.Iassumethatthereaderisfamiliarwiththe
basiccontrolstructuresofJavaorCandwithelementary
conceptssuchasvariablesanddecomposingaprobleminto
functions(methods).Onlyapre-calculuslevelofmathematics
isexpected.

WhyChooseThisBook?
Thisbookhaseverythingyouwouldeverwantinadata
structurestextbook:plentifulexercises,crystal-clearprose,
codeavailableon-line,andjusttherightamountofdepth.Of
course,everyauthorclaimsasmuch.Whatmakesthisbook
different?
Thisbookisdistinguishedbythefollowingfeatures:
UseofnewJava1.5features
Anunusuallylargenumberofdiagrams,drawninthe
UnifiedModelingLanguage(UML)
"Invertedpyramid"style,withthemostimportantmaterial
upfront
Gradualintroductionofabstractconcepts
Extensiveuseofgamesasexamples


[Pagexii]
Version1.5ofJavaaddsseverallong-awaitedfeaturestothe

language.Thesenewfeaturesareexplainedandusedinmany
examplesthroughoutthisbook.Specifically:
Thenewenhancedforloopallowsaprogrammerto
conciselysay,"Foreachelementofthisarrayor
Collection...."ThisisdiscussedinAppendixAand,for
Collections,inChapter5.
Primitivesarenowautomaticallyboxedandunboxed,
freeingprogrammersfromtheawkward
((Integer)(numbers.get(i))).intValue()
construction.ThisiscoveredinChapter2inthediscussion
ofreferencetypes.
Thenewjava.util.Scannerclass(AppendixA)finallymakes
itpossibletoreadinputfromthekeyboardwithouta
ridiculousamountofcode.
Thebiggestchangeisprobablytheintroductionofgeneric
types(Chapter4),whichallowaprogrammertospecifythe
elementtypeofacollection,improvingbothprogramclarity
andtypesafety.
Inexplainingconcepts,Iusemanydiagrams.Longstretchesof
text,code,andequationsmakefordryreading.Agooddiagram
canexplainanewconceptclearly,provideaninstantreview,
andserveasalandmarkwhenreviewingthetext.Sincethe
UnifiedModelingLanguagehasbecomethedefactostandard
forsoftwarediagrams,thediagramsinthisbookaredrawnina
subsetoftheUML.Ihavedeliberatelyleftouteven
intermediateUMLfeatures,suchasaccessleveltagsand


aggregationdiamonds,asIfeeltheywouldcausemore
confusionthanclarity.Thisnotationisintroducedgradually

(mostlyinthefirstpartofthebook)andreviewedinAppendix
B.
Arelatedgraphicfeatureistheuseoffontsforemphasisin
code.Manytextseitherprovidenofonthighlightingorusefonts
tohighlightkeywords.Thissyntaxhighlightingisusefulwhen
typingcode(helpingtopreventtypographicalerrors),butit
neithermakescodeeasiertoreadnoremphasizesimportant
passages.Iusebolditalictexttohighlightpartsofthecode
whichareofparticularinterestinthecurrentdiscussion.If
nothinginparticularisbeingemphasized,Ihighlightmethod
andfieldnamestodelineatethemajorsectionsofaclass.
Thisbookiswritteninthe"invertedpyramid"styletaughtto
journalists:themostimportantmaterialisatthefront,with
finerdetailsandmoreadvancedtopicsintroducedwitheach
chapter.Acoursecouldreasonablybestoppedafterany
chapter.Thisgivesinstructorsthefreedomtospeeduporslow
downasnecessary,withoutfearofnotgettingtoanimportant
topicbeforetheendofthecourse.
Manytextsoverwhelmthereaderwithtoomuchabstractionup
front.Thisisaneasymistaketomakeforfullytrained
computerscientists,whoprefertoreadaboutthebigpicture
beforedelvingintodetails.Ontheotherhand,studentswho
mustabsorbinheritance,polymorphism,recursion,andanalysis
ofalgorithmsbeforethey'vewrittenasingle"real"programare
likelytoloseinterest,ifnotconsciousness.Iconstantlyhear
studentsaskingformoreconcreteexamples,andI'venever
heardonecomplainabouttoomanyexamples.

[Pagexiii]
Withthistensioninmind,Ihavetriedtoprovideexamples

earlyineachchapter.Letthestudentshavecomplete,working


programstomesswithassoonaspossible.Abstractconcepts
aremucheasiertoabsorbinthecontextofaconcreteproblem.
Difficultconceptsarealsointroducedasgraduallyaspossible.
Forexample,thecallstackisdiscussedbeforeitappearsinthe
contextofrecursion.
Mostofmyexamplesaregames,ofteninvolvingdice,cards,
andboards.Gamescapturethestudents'imagination,giving
themsomereasontocareaboutthedatastructureoralgorithm
beingdiscussed.Whilesimpleenoughtoprogramwithoutpages
andpagesofcode,gamesofferamorerealisticchallengethan
antiseptictaskssuchasfindingagreatestcommondivisor.Near
themidpointofthetext,gamesinvolvingadictionaryoftensof
thousandsofwordsprovidecompellingmotivationforefficient
datastructuresandalgorithms.
Especiallynearthebeginningofthebook,Iworkthroughthe
developmentofeachproject,oftenprovidingmultipleversions
ofthecodeandconsideringalternatedesigns.Studentsthus
experiencetheprocessofcraftingprograms,ratherthanjust
theresults.Whilenovitalpartsoftheprogramareleftout,
someenhancements(suchascheckingforvalidinput)areleft
asproblems.
Complete,workingcodeforeveryprogramisprintedinthe
bookandavailableon-line.Irecall,asastudent,beingannoyed
whenthehardpartofanalgorithmordatastructurewasleftas
anexercise.It'sallhere,evencodeforB-trees;Iknowofno
otherundergraduatetextthatpresentsthismaterialatthis
levelofcompleteness.

Noclasseshavetobedownloadedinadvancetousethecodein
thisbook.Laterclassesmakeuseofearlierclasses.Ifdesired,
theselaterclassescanbeeasilyadaptedtousebuilt-inclasses
fromtheJavacollectionsframework;themethodnamesforthe
classesdevelopedinthebookarecongruent.


Myhopeisthat,bytheendofthetext,thereaderwillhave
gainedconsiderableskillinrapidlydevelopingcorrect,efficient,
general-purposeprograms.

Organization
Thisbookisdividedintofiveparts:object-oriented
programming,linearstructures,algorithms,treesand
collections,andadvancedtopics.
PartIintroducesobject-orientedprogramming,withone
chapteroneachofthethreemajorprinciples:encapsulation,
polymorphism,andinheritance.Useofthispartofthebook
mayvarygreatlyfromoneinstitutiontoanother.Whereobjects
aretaughtinCS1,thispartmaybecoveredveryquicklyor
skippedaltogether(althoughtherearefewstudentswho
wouldn'tbenefitfromareviewofthismaterial).Atother
institutions,whereCS1istaughtinCorsomeotherlanguage,
moretimemaybespentonthismaterial.Alternately,thispart
ofthebook(alongwithAppendixA)isgoodforashortcourse
introducingobject-orientedprogramming.
PartIIcoversstacks,queues,andlists,inbotharray-basedand
linkedimplementations.Thereaderisshownhowthese
structuresareusedandhowtobuildthem,thenwheretofind
themintheJavacollectionsframework.

InPartIII,thereaderbeginsthejourneyfrommere
programmingtocomputerscience.Analysisofalgorithmsis
introduced,includingasymptoticnotationandastep-by-step
procedureforanalyzingsimplealgorithms.Afterthisdifficult
material,thereadergetsabreakwitharelativelyshortchapter
onthesimplestsearchingandsortingalgorithms.Bythetime
recursionisintroduced,thereaderhasbeenpreparedwithan
understandingofthecallstack,anunderstandingofthesorting
problem,andtheabilitytoappreciatethebetterperformance


providedbyrecursivealgorithmssuchasmergesortand
Quicksort.

[Pagexiv]
PartIVfocusesondatastructures,coveringtreesandset
implementations(orderedlists,binarysearchtrees,andhash
tables).
AdvancedtopicsareaddressedinPartV,fromwhichinstructors
mayfreelychoosetheirfavorites.Amongthechoicesare
advancedlinearstructures,strings,advancedtrees,graphs,
memorymanagement,andissuesinvolvedwithdiskstorage.

Exercises,Problems,andProjects
Exercisesareprovidedattheendofmostsections.These
shouldnottakemorethanacoupleofminutestosolve.
Exercisesaregoodquestionstoposeduringclassoronexams.
Problemsareprovidedattheendofeachchapter.Theseare
slightlymoreinvolved,takingperhaps5or10minutestosolve.
Thesearegoodforexamsandhomework.

Finally,oneormoreprojectsaregivenattheendofeach
chapter.Thesewillusuallytakeanhourormore,andmake
goodstand-alonehomeworkorlabassignments.

Acknowledgments
Iwishtothank:mywifeHeather,forproofreadingaboveand
beyondthecallofdutyandforremindingmetoeat;Dan
Friedman,forconvincingmethatIwasn'tjokingwhenIbegan
writinganearlyversionofthisbookingraduateschool;James


Ernest(theSidSacksonofthetwenty-firstcentury),for
allowingmetousehisgamedesigns;AlanApt,forhisguidance
andforgivingmeashotatthebigtime;PaulPurdomand
DavidWise,forilluminatingsomeofthedarkercornersofdata
structuresandalgorithms;andallthosewhohaveprovided
comments,suggestions,andproofreadingthroughtheyears,
includingKevinandRebeccaDjang,JerryFranke,MattJadud,
SidKitchel,JimLevenick,countlesscomputersciencestudents
bothatIndianaUniversityandatLewis&ClarkCollege,andthe
anonymousreviewers.
PETERDRAKE
Portland,Oregon




[Page1]



PartI:Object-OrientedProgramming
Chapter1.Encapsulation
Chapter2.Polymorphism
Chapter3.Inheritance


[Page3]


Chapter1.Encapsulation
Thischapterintroducestheobject-orientedapproachto
softwaredevelopment.Section1.1discussesthesoftware
developmentprocessandtheideaofencapsulation:dividinga
programintodistinctcomponentswhichhavelimited
interaction.InSections1.2and1.3,wedevelopaprogramto
playthegameofBeetle.Section1.2introducesterminology
andconceptsrelatedtoobjectsaswewriteaclasstomodelthe
dieusedinthegame.Section1.3expandsonthis,developing
twomoreclassestocompletetheprogram.
SomereadersmaywishtoreadAppendixAbeforebeginning
thischapter.


[Page3(continued)]

1.1.SoftwareDevelopment
GoodPrograms
Whatarethefeaturesofagoodcomputerprogram?Itis
essentialthattheprogrambecorrect,doingwhatitis
supposedtodoandcontainingnobugs.Theprogramshouldbe

efficient,usingnomoretimeormemorythanisnecessary.
Theprogramshouldbegeneral-purpose,sothatwedon't
havetostartfromscratchthenexttimewebuildasimilar
program.Finally,allotherthingsbeingequal,theprogram
shouldberapidlydeveloped.Whiletherearesomechanges
whichwillfurtheroneofthesegoalsatnocost,itisoften
necessarytomaketradeoffs,assuggestedbyFigure1-1.

[Page4]
Figure1-1.Thereareoftentradeoffsbetweenthe
featuresofagoodcomputerprogram.

Wewouldlikeallofourprogramstobeperfectlycorrect.In


someapplications,suchasmedicalequipment,aircraft
navigation,andnuclearpowerplantcontrol,livesmayliterally
dependonthecorrectnessofsoftware.Inothers,suchas
gamesandwebbrowsers,theoccasionalcrashmaybemerely
anannoyance.Thebestwaytoensurecorrectnessisto
preciselyspecifyhowtheprogramissupposedtobehaveand
thenthoroughlytesttheprogramtoverifythatitdoesso.
Unfortunately,thiscantakeaprohibitiveamountoftime.
Practicalconcernsoftenleadtothereleaseofbuggysoftware.
Muchofthisbookconcernschoosingdatastructuresand
algorithmstomakeprogramsmoreefficient.Adatastructure
isawayoforganizinginformation(numbers,text,pictures,and
soon)inacomputer.Analgorithmisastep-by-stepprocess
fordoingsomething,writteneitherinplainEnglishorina
programminglanguage.(Westudyalgorithmsratherthan

programsbecause,whileprogramminglanguageschangeevery
fewyears,goodalgorithmsstayaroundfordecadesoreven
millennia.)
Datastructuresandalgorithmsareintimatelyintertwined.A
datastructuremaysupportefficientalgorithmsforsome
operations(suchascheckingwhethersomeitemispresent)but
notforothers(suchasremovinganitem).Conversely,afast
algorithmmayrequirethatdatabestoredinaparticularway.
Tomakethebestchoices,wewouldliketoknowasmuchas
possibleabouthowourprogramwillbeused.Whatkindsof
dataarewelikelytoencounter?Whichoperationswillbemost
common?Someofthemostefficientdatastructuresand
algorithmsarelimitedtospecifictasks,sochoosingthem
makesourprogramslessgeneral-purpose.
Ifaprogramistobeusedveryheavily,itmaybeworth
spendingsometimetooptimizeit,thatis,fine-tuneitto
maximizeefficiencygiventheexpecteddata,thehardwareon
whichitwillrun,andsoon.Thistradesdevelopmenttimeand
generalityforefficiency.


×