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

Object oriented data structures using java 4th edition

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 (21.66 MB, 714 trang )

www.ebook3000.com


Object-Oriented
Data Structures
using

Java



Fourth Edition

Nell Dale
University of Texas, Austin

Daniel T. Joyce
Villanova University

Chip Weems
University of Massachusetts,
Amherst


World Headquarters
Jones & Bartlett Learning
5 Wall Street
Burlington, MA 01803
978-443-5000

www.jblearning.com


Jones & Bartlett Learning books and products are available through most bookstores and online booksellers. To contact Jones & Bartlett
Learning directly, call 800-832-0034, fax 978-443-8000, or visit our website, www.jblearning.com.
Substantial discounts on bulk quantities of Jones & Bartlett Learning publications are available to corporations, professional associations, and other qualified organizations. For details and specific discount information, contact the special sales department at Jones &
Bartlett Learning via the above contact information or send an email to
Copyright © 2018 by Jones & Bartlett Learning, LLC, an Ascend Learning Company
All rights reserved. No part of the material protected by this copyright may be reproduced or utilized in any form, electronic or mechanical, including photocopying, recording, or by any information storage and retrieval system, without written permission from the copyright
owner.
The content, statements, views, and opinions herein are the sole expression of the respective authors and not that of Jones & Bartlett Learning, LLC. Reference herein to any specific commercial product, process, or service by trade name, trademark, manufacturer, or otherwise
does not constitute or imply its endorsement or recommendation by Jones & Bartlett Learning, LLC and such reference shall not be used for
advertising or product endorsement purposes. All trademarks displayed are the trademarks of the parties noted herein. Object-Oriented Data
Structures Using Java, Fourth Edition is an independent publication and has not been authorized, sponsored, or otherwise approved by the
owners of the trademarks or service marks referenced in this product.
09820-4
Production Credits
VP, Executive Publisher: David D. Cella
Acquisitions Editor: Laura Pagluica
Editorial Assistant: Taylor Ferracane
Director of Vendor Management: Amy Rose
Marketing Manager: Amy Langlais
VP, Manufacturing and Inventory Control: Therese Connell
Composition and Project Management: S4Carlisle Publishing Services

Cover Design: Kristin E. Parker
Text Design: Scott Moden
Rights & Media Specialist: Merideth Tumasz
Media Development Editor: Shannon Sheehan
Cover Image: © Ake13bk/Shutterstock
Printing and Binding: Edwards Brothers Malloy
Cover Printing: Edwards Brothers Malloy


Library of Congress Cataloging-in-Publication Data
Names: Dale, Nell (Nell B.), author. | Joyce, Daniel T., author. | Weems,
Chip., author.
Title: Object-oriented data structures using Java / Nell Dale, Daniel T.
Joyce, Chip Weems.
Description: Fourth edition. | Burlington, MA : Jones & Bartlett Learning,
[2017]
Identifiers: LCCN 2016025145 | ISBN 9781284089097 (casebound)
Subjects: LCSH: Object-oriented programming (Computer science) | Data
structures (Computer science) | Java (Computer program language)
Classification: LCC QA76.64 .D35 2017 | DDC 005.13/3--dc23 LC record available at
/>6048
Printed in the United States of America
20 19 18 17 16 10 9 8 7 6 5 4 3 2 1

www.ebook3000.com


To Alfred G. Dale
ND
To Kathy, Tom, and Julie, thanks for the love and support
DJ
To Lisa, Charlie, and Abby, thank you . . .
CW


© Ake13bk/Shutterstock

Preface
WelcometothefourtheditionofObject-Oriented Data Structures Using Java™.Thisbookpresentsthealgorithmic,programming,andstructuringtechniquesofatraditionaldatastructures

courseinanobject-orientedcontext.You’llfindthefamiliartopicsoflinkedlists,recursion,
stacks,queues,collections,indexedlists,trees,maps,priorityqueues,graphs,sorting,searching,
andcomplexityanalysis,allcoveredfromanobject-orientedpointofviewusingJava.Westress
softwareengineeringprinciplesthroughout,includingmodularization,informationhiding,data
abstraction,stepwiserefinement,theuseofvisualaids,theanalysisofalgorithms,andsoftware
verificationmethods.

To the Student
Youknowthatanalgorithmisasequenceofunambiguousinstructionsforsolvingaproblem.
Youcantakeaproblemofmoderatecomplexity,designasmallsetofclasses/objectsthatwork
togethertosolvetheproblem,codethemethodalgorithmsneededtomaketheobjectswork,and
demonstratethecorrectnessofyoursolution.
Algorithmsdescribeactions.Theseactionsmanipulatedata.Formostinterestingproblems
thataresolvedusingcomputers,thestructureofthedataisjustasimportantasthestructure
ofthealgorithmsusedtomanipulatethedata.Usingthistextyouwilldiscoverthattheway
youstructuredataaffectshowefficientlyyoucanusethedata;youwillseehowthenatureof
theproblemyouareattemptingtosolvedictatesyourstructuringdecisions;andyouwilllearn
aboutthedatastructuresthatcomputerscientistshavedevelopedovertheyearstohelpsolve
problems.

Object-Oriented Programming with Java
Ourprimarygoalistopresentboththetraditionalandmoderndatastructuretopicswithan
emphasisonproblemsolvingandsoftwaredesign.UsingtheJavaprogramminglanguageasa
vehicleforproblemsolutions,however,presentsanopportunityforstudentstoexpandtheir

www.ebook3000.com


Preface
familiaritywithamodernprogramminglanguageandtheobject-orientedparadigm.Asourdata

structurecoverageunfolds,weintroduceandusetheappropriateJavaconstructsthatsupportour
primarygoal.Startingearlyandcontinuingthroughoutthetext,weintroduceandexpandonthe
useofmanyJavafeaturessuchasclasses,objects,generics,polymorphism,packages,interfaces,
libraryclasses,inheritance,exceptions,andthreads.WealsouseUniversalModelingLanguage
(UML)classdiagramsthroughouttohelpmodelandvisualizeourobjects,classes,interfaces,
applications,andtheirinterrelationships.

Features
Data Abstraction Inthistextweviewourdatastructuresfromthreedifferentperspectives:
theirspecification,theirapplication,andtheirimplementation.Thespecificationdescribesthe
logicalorabstractlevel—what thelogicalrelationshipsamongthedataelementsareandwhat
operationscanbeperformedonthestructure.Theapplicationlevel,sometimescalledtheclient
level,isconcernedwithhowthedatastructureisusedtosolveaproblem—why theoperations
dowhattheydo.Theimplementationlevelinvolvesthecodingdetails—how thestructures
andoperationsareimplemented.Inotherwordswetreatourdatastructuresasabstractdata
types(ADTs).
Efficiency Analysis InChapter1weintroduceorderofgrowthefficiencyanalysisusingaunique
approachinvolvingtheinteractionoftwostudentsplayingagame.Timeandspaceanalysisis
consistentlyappliedthroughoutthetext,allowingustocompareandcontrastdatastructure
implementationsandtheapplicationsthatusethem.
Recursion Treatment Recursionisintroducedearly(Chapter3)andusedthroughouttheremainderofthetext.Wepresentadesignandanalysisapproachtorecursionbasedonanswering
threesimplequestions.Answeringthequestions,whicharebasedonformalinductivereasoning,
leadstheprogrammertoasolidrecursivedesignandprogram.
Interesting Applications Eightprimarydatastructures(stacks,queues,collections,indexed
lists,trees,maps,priorityqueues,andgraphs)aretreatedinseparatechaptersthatincludetheir
definition,severalimplementations,andoneormoreinterestingapplicationsbasedontheiruse.
Applicationsinvolve,forexample,balancedexpressions,postfixexpressions,imagegeneration
(new!),fractals(new!),queuesimulation,carddecksandgames(new!),textanalysis(new!),tree
andgraphtraversals,andbigintegers.
Robust Exercises Weaveragemorethan40exercisesperchapter.Theexercisesareorganizedby

chaptersectionstomakethemeasierforyoutomanage.Theyvaryinlevelofdifficulty,including
shortandlongprogrammingproblems(markedwith“programming-required”icons—oneicon
toindicateshortexercisesandtwoiconsforprojects),theanalysisofalgorithms,andproblems
toteststudents’understandingofabstractconcepts.Inthiseditionwehavestreamlinedthe
previousexercises,allowingustoaddevenmoreoptionsforyoutochoosefrom.Inparticular
wehaveaddedseverallargerprogrammingexercisestomanyofthechapters.
Input/Output Options ItisdifficulttoknowwhatbackgroundthestudentsusingadatastructurestextwillhaveinJavaI/O.Toallowallthestudentsusingourtexttoconcentrateonthe

v


vi

Preface
primarytopicofdatastructures,weusethesimplestI/Oapproachwecan,namelyacommand
lineinterface.However,tosupportthoseteachersandstudentswhoprefertoworkwithgraphicaluserinterfaces(GUIs),weprovideGUIsformanyofourapplications.Ourmodularapproach
toprogramdesignsupportsthisapproach—ourapplicationsseparatetheuserinterfacecode,
problemsolutioncode,andADTimplementationcodeintoseparateclasses.
Concurrency Coverage Wearepleasedtobeoneoftheonlydatastructurestextstoaddressthe
topicsofconcurrencyandsynchronization,whicharegrowinginimportanceascomputersystems
movetousingmorecoresandthreadstoobtainadditionalperformancewitheachnewgeneration.
WeintroducethistopicinSection4.9,“Concurrency,Interference,andSynchronization,”where
westartwiththebasicsofJavathreads,continuethroughexamplesofthreadinterferenceand
synchronization,andculminateinadiscussionofefficiencyconcerns.

New to the Fourth Edition
Thiseditionrepresentsamajorrevisionofthetext’smaterial,althoughthephilosophyandstyle
thatourloyaladoptershavegrowntoappreciateremainunchanged.Weremovedmaterialwe
feltwasredundantoroflesser/outdatedimportancetothecoretopicofdatastructures,added
newkeymaterial,andreworkedmuchofthematerialthatwekept.Althoughthelengthofthe

textbookwasreducedbyabout10%,thecoverageofdatastructureshasbeenexpanded.We
believethisneweditionisagreatimprovementoverpreviouseditionsandhopeyoudo,too.
Majorchangesinclude:
• SimplifiedArchitecture:WecontinuetousetheJavainterfaceconstructto
definetheabstractviewofourADTs,butwehavereducedthenumberoflevels
ofinheritance,simplifyingthearchitectureandmakingiteasiertounderstand
anduse.
• NewChapters:Chapter5,“TheCollectionADT,”andChapter8,“TheMapADT,”are
brandnew.TheCollectionADTmaterialintroducestheideaofadatastructureas
arepositoryandconcentratesonstorageandretrievalofdatabasedonkeyattributes.TheMapADThasbecomeincreasinglyimportantwiththeriseinpopularity
ofscriptinglanguageswithbuilt-inassociativearrays.
• NewSection:Section1.6,“ComparingAlgorithms:OrderofGrowthAnalysis,”was
completelyrewrittenandfeaturesanintroductiontoefficiencyanalysisdrivenby
agameplayedbetweentwostudents,plusanalysisofsequentialsearch,binary
search,andsequentialsortalgorithms.
• NewSections:Inresponsetoreader’ssuggestions,Chapter3,“Recursion,”features
twonewsections:Section3.3,“RecursiveProcessingofArrays,”isdevotedtorecursiveprocessingofarraysandSection3.4,“RecursiveProcessingofLinkedLists,”is
devotedtorecursiveprocessingoflinkedlists.Thesenewsectionsprovidepractical
examplesoftheuseofrecursion,beforethereadermovesontothelesspractical
butneverthelesspopularTowersofHanoiexamplecoveredinSection3.5,“Towers.”
• NewSection:Fractals!Afunsectionrelatedtorecursivelygeneratingfractal-based
imagesnowwrapsuptheexamplesofChapter3,“Recursion.”

www.ebook3000.com


Preface
• NewSections:Weadded“Variations”sectionstotheStack,Queue,Collection,List,
Tree,andMapchapters.IntheprimaryexpositionofeachoftheseADTswerecord
designdecisionsandspecifytheoperationstobesupportedbytheADT.Wealso

developoratleastdiscussvariousimplementationapproaches,inmostcaseshighlightingonearray-basedapproachandonereference/linked-list-basedapproach.
The“Variations”sectiondiscussesalternateapproachestodefining/implementing
theADTandinmostcasesreviewstheADTcounterpartsavailableinthestandard
JavaLibrary.SomeofthesesectionsalsointroducerelatedADTs,forexample,inthe
“Variations”sectionoftheCollectionchapterwedefineanddiscussboththeSet
andBagADTs.
• Glossary:Thetext’sglossaryhasalwaysbeenavailableonline.Withthiseditionwe
makeitavailableasAppendixE.Throughoutthetextwehighlightimportantterms
thatmightbeunfamiliartothestudentingreen,thefirsttimetheyarefeatured,to
indicatethattheirdefinitioncanbefoundintheglossary.

Prerequisite Assumptions
Inthisbook,weassumethatreadersarefamiliarwiththefollowingJavaconstructs:





Built-insimpledatatypesandthearraytype
Controlstructureswhile,do,for,if,andswitch
Creatingandinstantiatingobjects
Basicuser-definedclasses:
■ variablesandmethods
■ constructors,methodparameters,andthereturn statement
■ visibilitymodifiers
• CommonlyusedJavaLibraryClasses:Integer, Math, Random, Scanner,String,
andSystem

Chapter Content
Chapter 1 isallaboutGetting Organized.Anoverviewofobjectorientationstressesmechanismsfororganizingobjectsandclasses.TheJavaexceptionhandlingmechanisms,usedto

organizeresponsetounusualsituations,areintroduced.Datastructuresarepreviewedandthe
twofundamentallanguageconstructsthatareusedtoimplementthosestructures,thearray
andthereference(link/pointer),arediscussed.Thechapterconcludeswithalookatefficiency
analysis—howweevaluateandcomparealgorithms.
Chapter 2 presentsThe Stack ADT.Theconceptofabstractdatatype(ADT)isintroduced.
Thestackisviewedfromthreedifferentlevels:theabstract,application,andimplementation
levels.TheJavainterfacemechanismisusedtosupportthisthree-tieredview.Wealsoinvestigate
usinggenericstosupportgenerallyusableADTs.TheStackADTisimplementedusingbotharrays
andreferences.Tosupportthereference-basedapproachweintroducethelinkedliststructure.
Sampleapplicationsincludedeterminingifasetofgroupingsymbolsiswellformedandthe
evaluationofpostfixexpressions.

vii


viii

Preface
Chapter 3 discussesRecursion,showinghowrecursioncanbeusedtosolveprogramming
problems.Asimplethree-questiontechniqueisintroducedforverifyingthecorrectnessofrecursivemethods.Sampleapplicationsincludearrayprocessing,linkedlistprocessing,theclassic
TowersofHanoi,andfractalgeneration.Adetaileddiscussionofhowrecursionworksshowshow
recursioncanbereplacedwithiterationandstacks.
Chapter 4 presentsThe Queue ADT.Itisalsofirstconsideredfromitsabstractperspective,
followedbyaformalspecification,andthenimplementedusingbotharray-basedandreferencebasedapproaches.Exampleapplicationsincludeaninteractivetestdriver,apalindromechecker,
andsimulatingasystemofreal-worldqueues.Finally,welookatJava’sconcurrencyandsynchronizationmechanisms,explainingissuesofinterferenceandefficiency.
Chapter 5 definesThe Collection ADT.AfundamentalADT,theCollection,supportsstoring
informationandthenretrievingitlaterbasedonitscontent.Approachesforcomparingobjects
forequalityandorderarereviewed.Collectionimplementationsusinganarray,asortedarray,
andalinkedlistaredeveloped.Atextprocessingapplicationpermitscomparisonoftheimplementationapproachesforefficiency.The“Variations”sectionintroducestwomorewell-known
ADTs:theBagandtheSet.

Chapter 6 followsupwithamorespecificCollectionADT,The List ADT.Infact,thefollowing
twochaptersalsodevelopCollectionADTs.Iterationisintroducedhereandtheuseofanonymous
innerclassestoprovideiteratorsispresented.AswiththeCollectionADTwedeveloparray,sorted
array,andlinked-list–basedimplementations.The“Variations”sectionincludesanexampleof
howto“implement”alinkedlistwithinanarray.Applicationsincludeacarddeckmodelplus
somecardgames,andaBigIntegerclass.Thislatterapplicationdemonstrateshowwesometimes
designspecializedADTsforspecificproblems.
Chapter 7 developsThe Binary Search Tree ADT.Itrequiresmostofthechapterjustto
designandcreateourreference-basedimplementationofthisrelativelycomplexstructure.The
chapteralsodiscussestreesingeneral(includingbreadth-firstanddepth-firstsearching)andthe
problemofbalancingabinarysearchtree.Awidevarietyofspecial-purposeandself-balancing
treesareintroducedinthe“Variations”section.
Chapter 8 presentsThe Map ADT,alsoknownasasymboltable,dictionary,orassociative
array.Twoimplementationsaredeveloped,onethatusesanArrayListandtheotherthatusesa
hashtable.Alargepartofthechapterisdevotedtothislatterimplementationandtheimportant
conceptofhashing,whichprovidesaveryefficientimplementationofaMap.The“Variations”
sectiondiscussesamap-basedhybriddatastructureplusJava’ssupportforhashing.
Chapter 9 introducesThePriority Queue ADT,whichiscloselyrelatedtotheQueuebutwith
adifferentaccessingprotocol.Thisshortchapterdoespresentasortedarray-basedimplementation,butmostofthechapterfocusesonaclever,interesting,andveryefficientimplementation
calledaHeap.
Chapter 10 coversThe Graph ADT, includingimplementationapproachesandseveral
importantgraph-relatedalgorithms(depth-firstsearch,breadth-firstsearch,pathexistence,
shortestpaths,andconnectedcomponents).Thegraphalgorithmsmakeuseofstacks,queues,
andpriorityqueues,thusbothreinforcingearliermaterialanddemonstratingthegeneralusabilityofthesestructures.

www.ebook3000.com


Preface
Chapter 11 presents/reviewsanumberofSorting and Searching Algorithms.Thesorting

algorithmsthatareillustrated,implemented,andcomparedincludestraightselectionsort,two
versionsofbubblesort,insertionsort,quicksort,heapsort,andmergesort.Thesortingalgorithmsarecomparedusingefficiencyanalysis.Thediscussionofalgorithmanalysiscontinuesin
thecontextofsearching.Previouslypresentedsearchingalgorithmsarereviewedandnewones
aredescribed.

Organization
Chapter Goals Setsofknowledgeandskillgoalsarepresentedatthebeginningofeachchapter
tohelpthestudentsassesswhattheyhavelearned.
Sample Programs Numeroussampleprogramsandprogramsegmentsillustratetheabstract
conceptsthroughoutthetext.
Feature Sections Throughoutthetexttheseshortsectionshighlighttopicsthatarenotdirectly
partoftheflowofmaterialbutneverthelessarerelatedandimportant.
Boxed Notes Thesesmallboxesofinformationscatteredthroughoutthetexthighlight,supplement,andreinforcethetextmaterial,perhapsfromaslightlydifferentpointofview.
Chapter Summaries Eachchapterconcludeswithasummarysectionthatreviewsthemostimportanttopicsofthechapterandtiestogetherrelatedtopics.Somechaptersummariesincludea
UMLdiagramofthemajorinterfacesandclassesdevelopedwithinthechapter.
Appendices TheappendicessummarizetheJavareservedwordset,operatorprecedence,primitive
datatypes,theASCIIsubsetofUnicode,andprovideaglossaryofimportanttermsusedinthetext.
Website />Thiswebsiteprovidesaccesstothetext’ssourcecodefilesforeachchapter.Additionally,registeredinstructorsareabletoaccessselectedanswerstothetext’sexercises,atestitemfile,and
presentationslides.Pleasecontacttheauthorsifyouhavematerialrelatedtothetextthatyou
wouldliketosharewithothers.

ix


x

Preface

Acknowledgments
Wewouldliketothankthefollowingpeoplewhotookthetimetoreviewthistext:Mark

LlewellynattheUniversityofCentralFlorida,ChenglieHuatCarrollCollege,ValTannen
attheUniversityofPennsylvania,ChrisDovolisattheUniversityofMinnesota,MikeCoeat
PlanoSeniorHighSchool,MikelPettyatUniversityofAlabamainHuntsville,GeneSheppard
atGeorgiaPerimeterCollege,NoniBohonakattheUniversityofSouthCarolina–Lancaster,
JoseCordovaattheUniversityofLouisiana–Monroe,JudyGurkaattheMetropolitanState
CollegeofDenver,MikhailBrikmanatSalemStateUniversity,AmitavaKarmakeratUniversity
ofWisconsin–Stout,GuifengShaoatTennesseeStateUniversity,UrskaCvekatLouisianaState
UniversityatShreveport,PhilipC.DoughtyJr.atNorthernVirginiaCommunityCollege,Jeff
KimballatSouthwestBaptistUniversity,JeremyT.LanmanatNovaSoutheasternUniversity,
RaoLiatUniversityofSouthCarolinaAiken,LarryThomasatUniversityofToledo,andKaren
WorksatWestfieldStateUniversity.AspecialthankstoChristineShannonatCentreCollege,to
PhilLaMastraatFairfieldUniversity,toAllanGottliebofNewYorkUniversity,andtoJ.William
CuppatIndianaWesleyanUniversityforspecificcommentsleadingtoimprovementsinthe
text.ApersonalthankstoKristenObermyer,TaraSrihara,SeanWilson,ChristopherLezny,and
NagaLakshmi,allofVillanovaUniversity,plusKathy,Tom,andJulieJoyceforalloftheirhelp,
support,andproofreadingexpertise.
Avirtualbouquetofrosestotheeditorialandproductionteamswhocontributedsomuch,
especiallyLauraPagluica,TaylorFerracane,AmyRose,andPalaniappanMeyyappan.
ND
DJ
CW

www.ebook3000.com


© Ake13bk/Shutterstock

Contents
1


GettingOrganized 1
1.1

1.2

1.3

1.4

1.5

1.6

Classes, Objects, and Applications 2
Classes 2
TheUnifiedMethod 7
Objects 8
Applications 10
Organizing Classes 12
Inheritance 12
Packages 19
Exceptional Situations 22
HandlingExceptionalSituations 22
ExceptionsandClasses:AnExample 23
Data Structures 27
Implementation-DependentStructures 28
Implementation-IndependentStructures 29
WhatIsaDataStructure? 31
Basic Structuring Mechanisms 32
Memory 32

References 34
Arrays 38
Comparing Algorithms: Order of Growth Analysis
MeasuringanAlgorithm’sTimeEfficiency 44
ComplexityCases 45
SizeofInput 46
ComparingAlgorithms 47
OrderofGrowth 49

43


xii

Contents
SelectionSort 50
CommonOrdersofGrowth 53
Summary 54
Exercises 55

2

TheStackADT 67
2.1

2.2

2.3
2.4


2.5

2.6

2.7

2.8

2.9

Abstraction 68
InformationHiding 68
DataAbstraction 69
DataLevels 70
PreconditionsandPostconditions 71
JavaInterfaces 72
Interface-BasedPolymorphism 76
The Stack 78
OperationsonStacks 79
UsingStacks 79
Collection Elements 81
GenerallyUsableCollections 81
The Stack Interface 84
ExceptionalSituations 85
TheInterface 88
ExampleUse 89
Array-Based Stack Implementations 90
TheArrayBoundedStackClass 91
DefinitionsofStackOperations 93
TheArrayListStackClass 99

Application: Balanced Expressions 101
TheBalancedClass 102
TheApplication 107
TheSoftwareArchitecture 111
Introduction to Linked Lists 111
ArraysVersusLinkedLists 111
TheLLNodeClass 113
OperationsonLinkedLists 115
A Link-Based Stack 121
TheLinkedStackClass 122
ThepushOperation 124
ThepopOperation 127
TheOtherStackOperations 129
ComparingStackImplementations 131
Application: Postfix Expression Evaluator
Discussion 132
EvaluatingPostfixExpressions 133

132

www.ebook3000.com


Contents
PostfixExpressionEvaluationAlgorithm 134
ErrorProcessing 136
ThePostFixEvaluatorClass 137
ThePFixCLIClass 139
2.10 Stack Variations 142
RevisitingOurStackADT 142

TheJavaStackClassandtheCollectionsFramework 143
Summary 145
Exercises 147

3

Recursion 161
3.1

3.2

3.3
3.4

3.5

3.6

3.7

3.8

Recursive Definitions, Algorithms, and Programs
RecursiveDefinitions 162
RecursiveAlgorithms 163
RecursivePrograms 166
IterativeSolutionforFactorial 167
The Three Questions 167
VerifyingRecursiveAlgorithms 168
DeterminingInputConstraints 169

WritingRecursiveMethods 169
DebuggingRecursiveMethods 170
Recursive Processing of Arrays 170
BinarySearch 170
Recursive Processing of Linked Lists 174
RecursiveNatureofLinkedLists 175
TraversingaLinkedList 175
TransformingaLinkedList 178
Towers 182
TheAlgorithm 182
TheMethod 184
TheProgram 186
Fractals 186
AT-SquareFractal 187
Variations 190
Removing Recursion 191
HowRecursionWorks 191
TailCallElimination 195
DirectUseofaStack 196
When to Use a Recursive Solution 197
RecursionOverhead 198
InefficientAlgorithms 198
Clarity 200

162

xiii


xiv


Contents
Summary 202
Exercises 202

4 TheQueueADT
4.1

4.2
4.3

4.4

4.5

4.6

4.7

4.8

4.9

217

The Queue 218
OperationsonQueues 219
UsingQueues 219
The Queue Interface 220
ExampleUse 222

Array-Based Queue Implementations 223
TheArrayBoundedQueueClass 223
TheArrayUnboundedQueueClass 230
An Interactive Test Driver 234
TheGeneralApproach 234
ATestDriverfortheArrayBoundedQueueClass 235
UsingtheTestDriver 235
Link-Based Queue Implementations 237
TheEnqueueOperation 238
TheDequeueOperation 239
ACircularLinkedQueueDesign 241
ComparingQueueImplementations 242
Application: Palindromes 244
ThePalindromeClass 244
TheApplications 246
Queue Variations 248
ExceptionalSituations 248
TheGlassQueue 248
TheDouble-EndedQueue 251
DoublyLinkedLists 252
TheJavaLibraryCollectionFrameworkQueue/Deque 255
Application: Average Waiting Time 257
ProblemDiscussionandExample 258
TheCustomerClass 259
TheSimulation 262
TestingConsiderations 268
Concurrency, Interference, and Synchronization 268
TheCounterClass 270
JavaThreads 271
Interference 274

Synchronization 275
ASynchronizedQueue 277
ConcurrencyandtheJavaLibraryCollectionClasses 282

www.ebook3000.com


Contents
Summary 283
Exercises 284

5

TheCollectionADT 297
5.1

The Collection Interface 298
AssumptionsforOurCollections 299
TheInterface 299
5.2 Array-Based Collection Implementation 301
5.3 Application: Vocabulary Density 305
5.4 Comparing Objects Revisited 308
TheequalsMethod 308
TheComparableInterface 314
5.5 Sorted Array-Based Collection Implementation 315
ComparableElements 316
TheImplementation 317
ImplementingADTs“byCopy”or“byReference” 319
SampleApplication 323
5.6 Link-Based Collection Implementation 325

TheInternalRepresentation 325
TheOperations 326
ComparingCollectionImplementations 329
5.7 Collection Variations 330
TheJavaCollectionsFramework 330
TheBagADT 331
TheSetADT 333
Summary 336
Exercises 337

6 TheListADT
6.1

6.2

6.3

345

The List Interface 346
Iteration 346
AssumptionsforOurLists 348
TheInterface 348
ListImplementations 350
Array-BasedImplementation 350
Link-BasedImplementation 355
Applications:CardDeckandGames 361
TheCardClass 361
TheCardDeckClass 363
Application:ArrangingaCardHand 366

Application:HigherorLower? 369
Application:HowRareIsaPair? 370

xv


xvi

Contents
SortedArray-BasedListImplementation 373
TheInsertionSort 374
UnsupportedOperations 375
ComparatorInterface 376
Constructors 377
AnExample 378
6.5 ListVariations 380
JavaLibraryLists 380
LinkedListVariations 381
ALinkedListasanArrayofNodes 381
6.6 Application:LargeIntegers 386
LargeIntegers 386
TheInternalRepresentation 387
TheLargeIntListclass 388
TheLargeIntClass 393
AdditionandSubtraction 395
TheLargeIntCLIProgram 404
Summary 408
Exercises 410
6.4


7

TheBinarySearchTreeADT 421
7.1
7.2

7.3
7.4
7.5

7.6

7.7

7.8

Trees 423
TreeTraversals 426
Binary Search Trees 429
BinaryTrees 429
BinarySearchTrees 431
BinaryTreeTraversals 433
The Binary Search Tree Interface 435
TheInterface 436
The Implementation Level: Basics 439
Iterative Versus Recursive Method Implementations 443
RecursiveApproachtothesizeMethod 444
IterativeApproachtothesizeMethod 446
RecursionorIteration? 448
The Implementation Level: Remaining Observers 448

ThecontainsandgetOperations 449
TheTraversals 452
The Implementation Level: Transformers 455
TheaddOperation 455
TheremoveOperation 460
Binary Search Tree Performance 466
TextAnalysisExperimentRevisited 466
InsertionOrderandTreeShape 468

www.ebook3000.com


Contents
BalancingaBinarySearchTree 469
Application: Word Frequency Counter
TheWordFreqClass 472
TheApplication 473
7.10 Tree Variations 479
Application-SpecificVariations 479
BalancedSearchTrees 482
Summary 485
Exercises 487
7.9

8 TheMapADT

499

8.1
8.2


The Map Interface 501
Map Implementations 506
UnsortedArray 506
SortedArray 507
UnsortedLinkedList 507
SortedLinkedList 508
BinarySearchTree 508
AnArrayList-BasedImplementation 508
8.3 Application: String-to-String Map 512
8.4 Hashing 516
Collisions 518
8.5 Hash Functions 524
ArraySize 524
TheHashFunction 525
Java’sSupportforHashing 529
Complexity 530
8.6 A Hash-Based Map 530
TheImplementation 531
UsingtheHMapclass 538
8.7 Map Variations 539
AHybridStructure 540
JavaSupportforMaps 542
Summary 542
Exercises 543

9 ThePriorityQueueADT
9.1

9.2


551

The Priority Queue Interface 552
UsingPriorityQueues 552
TheInterface 553
Priority Queue Implementations 554
UnsortedArray 554

471

xvii


xviii

Contents
SortedArray 554
SortedLinkedList 556
BinarySearchTree 556
9.3 The Heap 556
9.4 The Heap Implementation 562
ANonlinkedRepresentationofBinaryTrees 562
ImplementingaHeap 564
TheenqueueMethod 567
ThedequeueMethod 569
ASampleUse 574
HeapsVersusOtherRepresentationsofPriorityQueues 575
Summary 576
Exercises 576


10 TheGraphADT

583

10.1 Introduction to Graphs 584
10.2 The Graph Interface 588
10.3 Implementations of Graphs 591
Array-BasedImplementation 591
LinkedImplementation 596
10.4 Application: Graph Traversals 597
Depth-FirstSearching 598
Breadth-FirstSearching 602
10.5 Application: The Single-Source Shortest-Paths Problem
Summary 611
Exercises 612

11

SortingandSearchingAlgorithms 621
11.1 Sorting 622
ATestHarness 623
11.2 Simple Sorts 625
SelectionSort 625
BubbleSort 631
InsertionSort 635
11.3 O(N log2N) Sorts 638
MergeSort 639
QuickSort 646
HeapSort 652

11.4 More Sorting Considerations
Testing 658
Efficiency 658
ObjectsandReferences 660

658

www.ebook3000.com

605


Contents
ComparingObjects 661
Stability 661
11.5 Searching 662
SequentialSearching 663
High-ProbabilityOrdering 663
SortedCollections 664
Hashing 665
Summary 666
Exercises 667

Appendix A: Java Reserved Words 673
Appendix B: Operator Precedence 674
Appendix C: Primitive Data Types 675
Appendix D: ASCII Subset of Unicode 676
Glossary 677
Index 683


xix


www.ebook3000.com


1

© Ake13bk/Shutterstock

CHAPTER

GettingOrganized
KnowledgeGoals
You should be able to
describe some benefits of object-oriented programming
describe the genesis of the Unified Method
explain the relationships among classes, objects, and applications
explain how method calls are bound to method implementations with respect to inheritance
describe, at an abstract level, the following structures: array, linked list, stack, queue, list, tree, map, and graph
identify which structures are implementation dependent and which are implementation independent
describe the difference between direct addressing and indirect addressing
explain the subtle ramifications of using references/pointers
explain the use of O notation to describe the amount of work done by an algorithm
describe the sequential search, binary search, and selection sort algorithms

SkillGoals
You should be able to
interpret a basic UML class diagram
design and implement a Java class

create a Java application that uses the Java class
use packages to organize Java compilation units
create a Java exception class
throw Java exceptions from within a class and catch them within an application that uses the class
predict the output of short segments of Java code that exhibit aliasing
declare, initialize, and use one- and two-dimensional arrays in Java, including both arrays of a primitive type and arrays of objects
given an algorithm, identify an appropriate size representation and determine its order of growth
given a section of code determine its order of growth


2

Chapter1 GettingOrganized
eforeembarkingonanynewproject,itisagoodideatopreparecarefully—to“get
organized.”Inthisϐirstchapterthatisexactlywhatwedo.Acarefulstudyofthetopics
ofthischapterwillprepareusforthematerialondatastructuresandalgorithms,using
theobject-orientedapproach,coveredintheremainderofthebook.

B

1.1

Classes,Objects,andApplications

Softwaredesignisaninteresting,challenging,andrewardingtask.Asabeginningstudent
ofcomputerscience,youwroteprogramsthatsolvedrelativelysimpleproblems.Much
ofyoureffortwentintolearningthesyntaxofaprogramminglanguagesuchasJava:the
language’sreservedwords,itsdatatypes,itsconstructsforselectionandlooping,andits
input/outputmechanisms.
Asyourprogramsandtheproblemstheysolvebecomemorecomplexitisimportant

tofollowasoftwaredesignapproachthatmodularizesyoursolutions—breakstheminto
coherentmanageablesubunits.Softwaredesignwasoriginallydrivenbyanemphasison
actions.Programsweremodularizedbybreakingthemintosubprogramsorprocedures/
functions.Asubprogramperformssomecalculationsandreturnsinformationtothecallingprogram,butitdoesnot“remember”anything.Inthelate1960s,researchersargued
that this approach was too limiting and did not allow us to successfully represent the
constructsneededtobuildcomplexsystems.
Two Norwegians, Kristen Nygaard and Ole-Johan Dahl, created Simula 67 in 1967.
It was the ϐirst language to support object-oriented programming. Object-oriented languages promote the object as the prime modularization mechanism. Objects represent
bothinformationandbehaviorandcan“remember”internalinformationfromoneuseto
thenext.Thiscrucialdifferenceallowsthemtobeusedinmanyversatileways.In2001,
NygaardandDahlreceivedtheTuringAward,sometimesreferredtoasthe“NobelPrize
ofComputing,”fortheirwork.
Thecapabilityofobjectstorepresentbothinformation(theobjectshaveattributes)
andbehavior(theobjectshaveresponsibilities)allowsthemtobeusedtorepresent“realworld”entitiesasvariedasbankaccounts,genomes,andhobbits.Theself-containednatureofobjectsmakesthemeasytoimplement,modify,andtestforcorrectness.
Objectorientationiscenteredonclassesandobjects.Objectsarethebasicrun-time
entitiesusedbyapplications.Anobjectisaninstantiationofaclass;alternatively,aclass
deϐinesthestructureofitsobjects.Inthissectionwereviewtheseobject-orientedprogrammingconstructsthatweusetoorganizeourprograms.

Classes
Aclassdeϐinesthestructureofanobjectorasetofobjects.Aclassdeϐinitionincludes
variables(data)andmethods(actions)thatdeterminethebehaviorofanobject.ThefollowingJavacodedeϐinesaDateclassthatcanbeusedtocreateandmanipulateDate
objects—forexample,withinaschoolcourse-schedulingapplication.TheDateclasscan
beusedtocreateDateobjectsandtolearnabouttheyear,month,ordayofanyparticular

www.ebook3000.com


1.1 Classes,Objects,andApplications
Date object.1 The class also provides
methods that return the Lilian Day Numberofthedate(thecodedetailshavebeen

omitted—seethefeaturesectiononLilian
Day Numbers for more information) and
returnastringrepresentationofthedate.

Authors’Convention
Java-reservedwords(whenusedassuch),user-defined
identifiers,classandfilenames,andsoon,appearin
this fontthroughouttheentiretext.

//---------------------------------------------------------------------// Date.java
by Dale/Joyce/Weems
Chapter 1
//
// Defines date objects with year, month, and day attributes.
//---------------------------------------------------------------------package ch01.dates;
public class Date
{
protected int year, month, day;
public static final int MINYEAR = 1583;
// Constructor
public Date(int newMonth, int newDay, int newYear)
{
month = newMonth; day = newDay; year = newYear;
}
// Observers
public int getYear() { return year; }
public int getMonth() { return month; }
public int getDay(){ return day; }
public int lilian()
{

// Returns the Lilian Day Number of this date.
// Algorithm goes here. Code is included with the program files.
// See Lilian Day Numbers feature section for details.
}
@Override2
public String toString()

1

The Java library includes a Date class, java.util.Date. However, the familiar properties of dates make them a natural
example to use in explaining object-oriented concepts. Here we ignore the existence of the library class, as if we must design
our own Date class.

2

The purpose of @Override is discussed in Section 1.2 “Organizing Classes.”

3


4

Chapter1 GettingOrganized
// Returns this date as a String.
{
return(month + "/" + day + "/" + year);
}
}

TheDateclassdemonstratestwokindsofvariables:instancevariablesandclassvariables.Theinstancevariablesofthisclassareyear,month,anddaydeclaredas

protected int year, month, day;

Theirvaluesvaryforeach“instance”ofanobjectoftheclass.Instancevariablesprovide
theinternalrepresentationofanobject’sattributes.
ThevariableMINYEARisdeclaredas
public static final int MINYEAR = 1583;

MINYEARisdeϐinedasbeingstatic,andthusitisaclassvariable.ItisassociateddirectlywiththeDateclass,insteadofwithobjectsoftheclass.Asinglecopyofaclassvariableismaintainedforallobjectsoftheclass.
Rememberthatthefinalmodiϐierstatesthatavariableisinitsϐinalformandcannotbemodiϐied;thusMINYEARisaconstant.Byconvention,weuseonlycapitalletters
whennamingconstants.Itisstandardproceduretodeclareconstantsasclassvariables.
Becausethevalueofthevariablecannotchange,thereisnoneedtoforceeveryobjectofa
classtocarryarounditsownversionofthevalue.Inadditiontoholdingsharedconstants,
classvariablescanbeusedtomaintaininformationthatiscommontoanentireclass.For
example,aBankAccountclassmayhaveaclassvariablethatholdsthenumberofcurrent
accounts.
IntheDateclassexample,theMINYEARconstantrepresentstheϐirstfullyearthatthewidely
Authors’Convention
used Gregorian calendar was in effect. The idea
Wehighlightimportanttermsthatmightbeunfamiliarto
here is that programmers should not use the
thestudentingreen,thefirsttimetheyarefeatured,to
indicatethattheirdefinitioncanbefoundintheglossary
class to represent dates that predate that year.
inAppendixE.
WelookatwaystoenforcethisruleinSection1.3
“Exceptional Situations,” where we discuss handlingexceptionalsituations.
The methods of the class are Date, getYear, getMonth, getDay, lilian, and
toString.NotethattheDatemethodhasthesamenameastheclass.Recallthatthis
meansitisaspecialtypeofmethod,calledaclassconstructor.Constructorsareusedto
createnewinstancesofaclass—thatis,toinstantiateobjectsofaclass.Theothermethodsareclassiϐiedasobservermethods,becausethey“observe”andreturninformation

basedontheinstancevariablevalues.Othernamesforobservermethodsare“accessor”
methodsand“getters,”asinaccessingorgettinginformation.Methodsthatsimplyreturn
thevalueofaninstancevariable,suchasgetYear()inourDateclass,areverycommon
andalwaysfollowthesamecodepatternconsistingofasinglereturnstatement.Forthis
reasonwewillformatsuchmethodsasasinglelineofcode.Inadditiontoconstructors

www.ebook3000.com


×