Fourth Edition Data Structures and Algorithm Analysis in C ++ This page intentionally left blank Fourth Edition Data Structures and Algorithm Analysis in C ++ Mark Allen Weiss Florida International University Boston Columbus Indianapolis NewYork SanFrancisco UpperSaddleRiver Amsterdam CapeTown Dubai London Madrid Milan Munich Paris Montreal Toronto Delhi MexicoCity SaoPaulo Sydney HongKong Seoul Singapore Taipei Tokyo EditorialDirector,ECS:MarciaHorton CoverDesigner:BruceKenselaar ExecutiveEditor:TracyJohnson PermissionsSupervisor:MichaelJoyce EditorialAssistant:JenahBlitz-Stoehr PermissionsAdministrator:JenellForschler DirectorofMarketing:ChristyLesko CoverImage:(cid:2)c De-kay|Dreamstime.com MarketingManager:YezAlayan MediaProjectManager:RenataButera SeniorMarketingCoordinator:KathrynFerranti Full-ServiceProjectManagement:IntegraSoftware MarketingAssistant:JonBryant ServicesPvt.Ltd. DirectorofProduction:ErinGregg Composition:IntegraSoftwareServicesPvt.Ltd. SeniorManagingEditor:ScottDisanno TextandCoverPrinter/Binder:CourierWestford SeniorProductionProjectManager:MarilynLloyd ManufacturingBuyer:LindaSager ArtDirector:JayneConte Copyright(cid:2)c 2014,2006,1999PearsonEducation,Inc.,publishingasAddison-Wesley.Allrightsreserved. PrintedintheUnitedStatesofAmerica.ThispublicationisprotectedbyCopyright,andpermissionshouldbe obtainedfromthepublisherpriortoanyprohibitedreproduction,storageinaretrievalsystem,ortransmission inanyformorbyanymeans,electronic,mechanical,photocopying,recording,orlikewise.Toobtain permission(s)tousematerialfromthiswork,pleasesubmitawrittenrequesttoPearsonEducation,Inc., PermissionsDepartment,OneLakeStreet,UpperSaddleRiver,NewJersey07458,oryoumayfaxyourrequest to201-236-3290. Manyofthedesignationsbymanufacturersandsellerstodistinguishtheirproductsareclaimedastrademarks. Wherethosedesignationsappearinthisbook,andthepublisherwasawareofatrademarkclaim,the designationshavebeenprintedininitialcapsorallcaps. LibraryofCongressCataloging-in-PublicationData Weiss,MarkAllen. DatastructuresandalgorithmanalysisinC++/MarkAllenWeiss,FloridaInternationalUniversity.—Fourth edition. pagescm ISBN-13:978-0-13-284737-7(alk.paper) ISBN-10:0-13-284737-X(alk.paper) 1.C++(Computerprogramlanguage)2.Datastructures(Computerscience)3.Computeralgorithms.I.Title. QA76.73.C153W462014 (cid:3) 005.73—dc23 2013011064 10 9 8 7 6 5 4 3 2 1 ISBN-10: 0-13-284737-X www.pearsonhighered.com ISBN-13:978-0-13-284737-7 To my kind, brilliant, and inspiring Sara. This page intentionally left blank CONTENTS Preface xv Chapter 1 Programming: A General Overview 1 1.1 What’sThisBookAbout? 1 1.2 MathematicsReview 2 1.2.1 Exponents 3 1.2.2 Logarithms 3 1.2.3 Series 4 1.2.4 ModularArithmetic 5 1.2.5 ThePWord 6 1.3 ABriefIntroductiontoRecursion 8 1.4 C++Classes 12 1.4.1 BasicclassSyntax 12 1.4.2 ExtraConstructorSyntaxandAccessors 13 1.4.3 SeparationofInterfaceandImplementation 16 1.4.4 vectorandstring 19 1.5 C++Details 21 1.5.1 Pointers 21 1.5.2 Lvalues,Rvalues,andReferences 23 1.5.3 ParameterPassing 25 1.5.4 ReturnPassing 27 1.5.5 std::swapandstd::move 29 1.5.6 TheBig-Five:Destructor,CopyConstructor,MoveConstructor,Copy Assignmentoperator=,MoveAssignmentoperator= 30 1.5.7 C-styleArraysandStrings 35 1.6 Templates 36 1.6.1 FunctionTemplates 37 1.6.2 ClassTemplates 38 1.6.3 Object,Comparable,andanExample 39 1.6.4 FunctionObjects 41 1.6.5 SeparateCompilationofClassTemplates 44 1.7 UsingMatrices 44 1.7.1 TheDataMembers,Constructor,andBasicAccessors 44 1.7.2 operator[] 45 vii viii Contents 1.7.3 Big-Five 46 Summary 46 Exercises 46 References 48 Chapter 2 Algorithm Analysis 51 2.1 MathematicalBackground 51 2.2 Model 54 2.3 WhattoAnalyze 54 2.4 Running-TimeCalculations 57 2.4.1 ASimpleExample 58 2.4.2 GeneralRules 58 2.4.3 SolutionsfortheMaximumSubsequence SumProblem 60 2.4.4 LogarithmsintheRunningTime 66 2.4.5 LimitationsofWorst-CaseAnalysis 70 Summary 70 Exercises 71 References 76 Chapter 3 Lists, Stacks, and Queues 77 3.1 AbstractDataTypes(ADTs) 77 3.2 TheListADT 78 3.2.1 SimpleArrayImplementationofLists 78 3.2.2 SimpleLinkedLists 79 3.3 vectorandlistintheSTL 80 3.3.1 Iterators 82 3.3.2 Example:UsingeraseonaList 83 3.3.3 const_iterators 84 3.4 Implementationofvector 86 3.5 Implementationoflist 91 3.6 TheStackADT 103 3.6.1 StackModel 103 3.6.2 ImplementationofStacks 104 3.6.3 Applications 104 3.7 TheQueueADT 112 3.7.1 QueueModel 113 3.7.2 ArrayImplementationofQueues 113 3.7.3 ApplicationsofQueues 115 Summary 116 Exercises 116 Contents ix Chapter 4 Trees 121 4.1 Preliminaries 121 4.1.1 ImplementationofTrees 122 4.1.2 TreeTraversalswithanApplication 123 4.2 BinaryTrees 126 4.2.1 Implementation 128 4.2.2 AnExample:ExpressionTrees 128 4.3 TheSearchTreeADT—BinarySearchTrees 132 4.3.1 contains 134 4.3.2 findMinandfindMax 135 4.3.3 insert 136 4.3.4 remove 139 4.3.5 DestructorandCopyConstructor 141 4.3.6 Average-CaseAnalysis 141 4.4 AVLTrees 144 4.4.1 SingleRotation 147 4.4.2 DoubleRotation 149 4.5 SplayTrees 158 4.5.1 ASimpleIdea(ThatDoesNotWork) 158 4.5.2 Splaying 160 4.6 TreeTraversals(Revisited) 166 4.7 B-Trees 168 4.8 SetsandMapsintheStandardLibrary 173 4.8.1 Sets 173 4.8.2 Maps 174 4.8.3 Implementationofsetandmap 175 4.8.4 AnExampleThatUsesSeveralMaps 176 Summary 181 Exercises 182 References 189 Chapter 5 Hashing 193 5.1 GeneralIdea 193 5.2 HashFunction 194 5.3 SeparateChaining 196 5.4 HashTableswithoutLinkedLists 201 5.4.1 LinearProbing 201 5.4.2 QuadraticProbing 202 5.4.3 DoubleHashing 207 5.5 Rehashing 208 5.6 HashTablesintheStandardLibrary 210
Description: