ebook img

Data structures outside in with Java PDF

512 Pages·2.93 MB·English
Save to my drive
Quick download
Download
Most books are stored in the elastic cloud where traffic is expensive. For this reason, we have a limit on daily download.

Preview Data structures outside in with Java

DATA STRUCTURES OUTSIDE IN ™ With Java Sesh Venugopal Rutgers University UpperSaddleRiver,NewJersey07458 LibraryofCongressCataloging-in-PublicationData Venugopal,Sesh. DataStructuresOutsideInwithJava/SeshVenugopal. p.cm. ISBN0-13-198619-8 1.Datastructures(Computerscience)2.Java(Computerprogramlanguage) I.Title. QA76.9.D35V462006 005.13(cid:2)3–dc22 2006031108 VicePresidentandEditorialDirector,ECS:MarciaJ.Horton ExecutiveEditor:TracyDunkelberger AssociateEditor:CaroleSnyder EditorialAssistant:ChristiannaLee ExecutiveManagingEditor:VinceO’Brien ManagingEditor:CamilleTrentacoste ProductionEditor:JohnShannon DirectorofCreativeServices:PaulBelfanti CreativeDirector:JuanLopez CoverDesignDirector:JayneConte CoverDesigner:BruceKenselaar ManagingEditor,AVManagementandProduction:PatriciaBurns ArtEditor:GregoryDulles Director,ImageResourceCenter:MelindaReo Manager,RightsandPermissions:ZinaArabia Manager,VisualResearch:BethBrenzel Manager,CoverVisualResearchandPermissions:KarenSanatar ManufacturingManager,ESM:AlexisHeydt-Long ManufacturingBuyer:LisaMcDowell ExecutiveMarketingManager:RobinO’Brien MarketingAssistant:MackPatterson ©2007PearsonEducation,Inc. PearsonPrenticeHall PearsonEducation,Inc. UpperSaddleRiver,NJ07458 Allrightsreserved.Nopartofthisbookmaybereproducedinanyformorbyanymeans,without permissioninwritingfromthepublisher. PearsonPrenticeHall™isatrademarkofPearsonEducation,Inc. Allothertradmarksorproductnamesarethepropertyoftheirrespectiveowners. Theauthorandpublisherofthisbookhaveusedtheirbesteffortsinpreparingthisbook.Theseefforts includethedevelopment,research,andtestingofthetheoriesandprogramstodeterminetheir effectiveness.Theauthorandpublishermakenowarrantyofanykind,expressedorimplied,withregardto theseprogramsorthedocumentationcontainedinthisbook.Theauthorandpublishershallnotbeliablein anyeventforincidentalorconsequentialdamagesinconnectionwith,orarisingoutof,thefurnishing, performance,oruseoftheseprograms. PrintedintheUnitedStatesofAmerica 10 9 8 7 6 5 4 3 2 1 ISBN: 0-13-198619-8 PearsonEducationLtd.,London PearsonEducationAustraliaPty.Ltd.,Sydney PearsonEducationSingapore,Pte.Ltd. PearsonEducationNorthAsiaLtd.,HongKong PearsonEducationCanada,Inc.,Toronto PearsonEducacio´ndeMexico,S.A.deC.V. PearsonEducation—Japan,Tokyo PearsonEducationMalaysia,Pte.Ltd. PearsonEducation,Inc.,UpperSaddleRiver,NewJersey Tomy motherandfather This page intentionally left blank Preface Therearetwobroadapproachestostudyingdatastructures. Oneisthe‘‘inside-out’’approachinwhichtheimplementationofthedatastructure, i.e.,howitisbuilt,islearnedeitherbeforeorinconjunctionwithitsapplicationtoproblem solving.Inotherwords,startfromthenucleusofthedatastructureandbuildoutwardto itsuseinaproblem. Theinside-outapproach,however,isdiscordantwiththemannerinwhichsoftware isbuiltinpracticeoutoflibrariesofobjectsthatareknownonlythroughtheirapplication programming interfaces (APIs). Here, the ‘‘outside-in’’ approach becomes the norm: a component orobjectisfirst—andoftenonly—seenviaits interface,whichcharacterizes itsbehaviorandthereforeitssuitabilityforagivenapplication.Thatis,whatacomponent doesprecedeshowitisbuilt. Outside-in:Fromprice-taggedinterfacetoimplementation In this book, we are interested in the interface as well as the implementation of data structures. We follow the outside-in approach to presenting them because it will enable students to easily apply in practical software development what they learn in class. Our approachisoutlinedinthefollowingsequenceofsteps. 1. Introduceadatastructurebynarratingitspropertiesanduseinapplications. This step familiarizes the student with the characteristic behavior of the data structure,settingthestagefortheencapsulationofdataandoperationsintoaJava class. 2. Formalizethecharacteristicpropertiesofadatastructurebypresentingthepublic interfaceofaJavaclassthatimplementsthedatastructure. This step defines the set of operations that may be applied on the data structure, formulated from the discussion in Step 1. With the interface, there also comes a ‘‘pricetag’’—therunningtimesoftheinterfaceoperations. Thepricetagisanimportantconsiderationintheselectionofdatastructuresforan application. It may be argued that the price tag determination may only be made afterthedatastructureisimplemented. Whilethisistrue,theoutside-inapproach thatisusedtobuildsoftwareinpracticetypicallyseparatesthegroupofpeoplewho work with the outside from the group of people who build the inside. The outside group must rely on all, and only, that information that comes with the interface. Havingapricetagwiththeinterfaceiscriticalfortheoutsidegrouptoevaluateand choosethebestobjectspossiblefortheapplicationathand. Tobeconsistentwiththisapproach,wehaveattachedthepricetagtotheinterface, butmadeaworkingcompromise:intheinterface,specifytheminimalrequirements of the implementation so that the running times of the operations stay within the pricetag. We admit that this blurs the separation between interface and implementation, whilerecognizingthatpartoftheissueisalsothatthesameperson—thestudent—is v vi Preface working with both the outside and the inside, albeit at different times. The best wayforthestudenttoapproachtheinterface-implementation separationistofirst imagine that he or she is a client of the data structure, with full cognizance of the interface and the price tag, and then imagine being the implementor of the data structure, who has been told whatlimitations (price tag) to work with to build the structure. 3. Further illustrate the use of a data structure by writing Java applications using its classinterfacepresentedinStep2. This step gives the student a clear practical understanding of how to build an application in Java using a data structure whose public interface is known, but whoseinternalimplementationishidden. Steps 2 and 3 strongly emphasize the interface of a data structure. By repeatedly building applications using only thepublic interfaceofdata structures,the student gets a practical feel for software development using components whose internal implementationdetailsneednot(andindeed,maynot)beavailable. 4. Design and implement the data structure, i.e., develop the code for the Java class whoseinterfacewaspresentedinStep2,analyzetherunningtimesofitsoperations, andverifythemagainstthepricetag. Thisstepemphasizescodereuseinoneoftwoforms:(a)composition:usingprevious data structuresas component (Java)objects inbuilding, or composing, a new data structure, or (b) inheritance: building a new data structure by inheriting from a previouslybuiltdatastructure(Javaclass). Whilewearefollowing anoutside-inapproach,this‘‘in’’partdoesnotdegenerate into using classes from the Java collections framework. Instead, it is on an equal footingwiththe‘‘outside’’part,withadetailedunderstandingoftheimplementation sothatthestudentlearnsallaspectsofbuildingdatastructures,includingevaluating thetradeoffsinvolvedinchoosingamongasetofcandidateimplementations. Apart from providing a consistent pedagogical form, these steps help students to understand and apply the important object-oriented design principles of encapsulation, separationofinterfacefromimplementation,andcodereuse. PrerequisitesinJava This book assumes a CS1-level background in Java 1.5, with the following specific coverage: program structure, data types, control structures for decision and repetition, includingtheif,if-else,for,while,andrepeatstatements,andarrays.Italsoassumes thatthestudentisfamiliarwiththewidelyusedStringclass. Chapter 1 is a Java primer on object-oriented programming that starts by assum- ing this CS1-level background, and introduces objects and classes, inheritance, the Object class, exceptions, core input and output features, class packaging, and access control. In the context of input/output, the java.util.StringTokenizer and the java.util.Scanner (new to Java 1.5) classes are described, with a discussion of their typicalusage. Preface vii Theprimeralsointroducesspecificallydesign-orientedfeatures,includingpolymor- phism,abstractclasses,andinterfaces. The last section discusses the new Java 1.5 generics, an indispensable tool for buildingusableandrobustdatastructures.Thisdiscussionalsodetailsthedesignanduse of the java.util.ArrayList class, which is a very useful component in implementing containerstructures,orcollections. Pathsthroughthebook Anessentialcoursefocusingonthebasicdatastructuresandsortingalgorithms,preceded by reviewing/learning the required Java tools and techniques in two weeks, could cover Chapters1–10,skippingSection10.7(AVLTree),andChapters12–13,skippingSections 13.3(Heapsort)and13.4(Radixsort). A course that could conduct the Java due diligence in lab instead of lecture could add Heap from Chapter 11, and Heapsort and Radix sort from Sections 13.3 and 13.4 respectively. AdvancedmaterialcouldbeincorporatedbycoveringAVLtreesfromSection10.7, andChapters14and15ongraphs.Incaseoftimelimitation,Chapter14wouldsufficeto familiarizestudentswithgraphalgorithms,whileleavingouttheimplementation details ofChapter15. A two-course sequence could cover the entire book, including much of the Java backgroundmaterialinChapter1.ThefirstcoursecouldcoverChapters1through9,up to and including Binary Tree/General Tree, and the second could cover the rest of the chapters,startingwithBinarySearchTree/AVLTreeofChapter10. Pedagogicalstructures. • Every chapter, except the preliminary Chapters 1 and 2, begins with a list of Learning Objectives.Thisgivesapreciseoverviewofthelearningmaterialinthe chapter. • Keypointsineverychapterarepresentedinthefollowingformat: Thesekeypointsarealsoitemizedintheend-of-chaptersummary. • Public interfaces of Java classes for data structures are presented as figures in the followingformat: Class classname Constructors Signatureanddescriptionofeachpublicconstructor Methods Runningtime(pricetag),signature,anddescriptionofeachpublicmethod viii Preface • EverycompleteJavaclassimplementationispresentedinthefollowingstyle: ClassFilenumber ClassFileName Classoutline,withsomeconstructors/methodspossiblyfilledin • Throughoutthebook,weusealgorithmswritteninpseudo-code,providinglanguage- independent descriptions of processes. These algorithms appear with a header of theform: Algorithm name of algorithm Thenotationsusedinthepseudo-codeareself-explanatory. • EverychapterexceptChapter2concludeswithalistingofSummarypoints.These includethekeypointsinthechapter,aswellasotherimportantpointstoremember, includingspecificJavaissues. • EverychapterexceptChapter2teststhestudent’sunderstandingofthematerialin theformofexercisesandprogrammingproblems: • Exercises, which are, for the most part, conceptual language-independent material, especiallyfocusingonwork-through reviews,abstractdesignissues, andtime-spaceanalysis. • ProgrammingProblems,whichfocusonbuildingJavaclasses,especiallyfocus- ingondesign/implementationalternativesandcodereuse. Acknowledgments IwouldliketothanktheDataStructuresteamsintheComputerSciencedepartmentat Rutgers University with whom I have taught this course for over more than a decade, and who have provided direct as well as indirect input that has helped shape this book. Special thanks to current and former faculty members Diane Souvaine, Ken Kaplan, MilesMurdocca,andDonSmithfordiscussingandreviewingthecontent. Many thanks to my friends and former graduate student colleagues Nathalie Japkowicz,GeorgeKatsaros,andDanArenaforcarefullyreviewingtheinitialC++draft, Gabriela Hristescu for providing help with typesetting aspects, and Sri Divakaran for reviewing parts of the Java manuscript. Several students in my data structures class of Fall 1997 readthe firstcomplete draft of this book and gave valuable feedback. Thanks tothemall,especiallyAlexChang,forbeingsuchatremendouslyloyalfanofthebook. ThanksalsotothestudentsinFall2002andSpring2003whopointedoutvariouserrors andothershortcomingsinanearlierversionthatwascustomizedforRutgers. Thanks are also due to the Data Structures faculty at Middlesex County College, and my former colleagues when I was working at Lucent Technologies with whom I discussed the material in this book at some point or the other. Special thanks to Tom WalshatLucentforcheeringmeon. Thankstoallthereviewerswhohelpedmakethisabetterbook:BarbaraGoldner at North Seattle Community College, Mark Llewellyn at University of Central Florida, ChrisDovolisatUniversityofMinnesota,IyadA.AjwaatAshlandUniversity,Minseok Kwon at Rochester Institute of Technology, George Rouskas at North Carolina State Preface ix University, Roxanne Canosa at Rochester Institute of Technology, Mary Horstman at WesternIllinoisUniversity,RayWhitneyatUniversityofMaryland,UniversityCollege, andRobertP.BurtonatBrighamYoungUniversity. TheeditorialteamatPrenticeHallhavesupportedmeinallaspectsofthisproject. Thanks to my editor Tracy Dunkelberger for believing that this book project would be a worthwhile enterprise, for her cheery confidence that kept me on an even keel, and formakingthisbookreal.ThankstoChristiannaLeeandCaroleSnyderforguidingme through the review process, and for responding to all my questions with patience and grace. John Shannon, Irwin Zucker, Camille Trentacoste and the production staff at Laserwordshelpedcorrectthenumeroustypographicalandgrammaticalerrorsthathad crept into the book, and formatted the pages to make sure they were presentable. Due totheirdiligenceandexpertise,you,dearreader,aresparedmyinadvertentmistakesor plainignoranceintheseareas.Forthis,mysincereappreciationandthankstoallofthem. I am deeply grateful to the members of my family and that of my wife’s for their adviceandencouragement,andforbeingtheretopepmeupwhenthingsdidn’tseemto begoingtoowellattimes.Iwouldspeciallyliketothankmyparents,mymother-in-law, and my wife’s grandparents for their constant support. Above all, thanks to my father, C.N. Venugopal, and to my wife’s grandfather, Dr. Hayrettin Tanacan, for their special participation. Although both of them are far removed from computers in general, and Data Structures in particular, they took the pains to go through my book to try and understandexactlywhatitwasthatIwastryingtowritethatwastakingsolong! Thankstomywife,ZehraTulin,forherhelpinmanywaysduringthewritingofthis book,andmoreimportantly,forherloveandsupportatalltimes.Andanextrabighug tomysonAmarwhoseunfailingprideinhisdadspursmeon. Finally,thankstoallthestudentswhotookmyclassesinvarioussubjectsatRutgers University and Middlesex County College over the years. They have been instrumental inmygrowthasaneducator,andIhopethisbookcanserveasatokenofmygratitudeto eachandeveryoneofthem. Inclosing,Iwouldbeveryhappytohearfromyouaboutthisbook—whatyouliked, whatyoudidnotcarefor,andtheerrorsyoufound,ifany.Youcanreachmebyemailat sesh [email protected]. SeshVenugopal Piscataway,NewJersey November,2006

See more

The list of books you might like

Most books are stored in the elastic cloud where traffic is expensive. For this reason, we have a limit on daily download.