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

teach yourself data structures and algorithms in 24 hours - robert lafore

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 (5.59 MB, 548 trang )

TeamLRN
201 West 103rd St., Indianapolis, Indiana, 46290 USA
Robert Lafore
Data Structures
and Algorithms
in
24
Hours
TeachYourself
00 72316331 FM 10/31/02 6:54 AM Page i
Sams Teach Yourself Data Structures and
Algorithms in 24 Hours
Copyright © 1999 by Sams Publishing
All rights reserved. No part of this book shall be reproduced, stored in a
retrieval system, or transmitted by any means, electronic, mechanical, photo-
copying, recording, or otherwise, without written permission from the pub-
lisher. No patent liability is assumed with respect to the use of the information
contained herein. Although every precaution has been taken in the preparation
of this book, the publisher and author assume no responsibility for errors or
omissions. Neither is any liability assumed for damages resulting from the use
of the information contained herein.
International Standard Book Number: 0-672-31633-1
Library of Congress Catalog Card Number: 98-83221
Printed in the United States of America
First Printing: May 1999
01 00 99 4 3 2 1
Trademarks
All terms mentioned in this book that are known to be trademarks or service
marks have been appropriately capitalized. Sams Publishing cannot attest to
the accuracy of this information. Use of a term in this book should not be
regarded as affecting the validity of any trademark or service mark.


Warning and Disclaimer
Every effort has been made to make this book as complete and as accurate as
possible, but no warranty or fitness is implied. The information provided is on
an “as is” basis. The authors and the publisher shall have neither liability or
responsibility to any person or entity with respect to any loss or damages aris-
ing from the information contained in this book or from the use of the CD-
ROM or programs accompanying it.
EXECUTIVE EDITOR
Brian Gill
DEVELOPMENT EDITOR
Jeff Durham
MANAGING EDITOR
Jodi Jensen
PROJECT EDITOR
Tonya Simpson
COPY EDITOR
Mike Henry
INDEXER
Larry Sweazy
PROOFREADERS
Mona Brown
Jill Mazurczyk
TECHNICAL EDITOR
Richard Wright
SOFTWARE DEVELOPMENT
SPECIALIST
Dan Scherf
INTERIOR DESIGN
Gary Adair
COVER DESIGN

Aren Howell
COPY WRITER
Eric Borgert
LAYOUT TECHNICIANS
Brian Borders
Susan Geiselman
00 72316331 FM 10/31/02 6:54 AM Page ii
TeamLRN
Contents at a Glance
Introduction 1
PART IINTRODUCING DATA STRUCTURES AND ALGORITHMS 9
Hour 1 Overview of Data Structures and Algorithms 11
2Arrays 31
3Ordered Arrays 51
4The Bubble Sort 75
5The Insertion Sort 89
PART II ABSTRACT DATA TYPES 105
Hour 6 Stacks 107
7 Queues and Priority Queues 125
8 Linked Lists 145
9 Abstract Data Types 165
10 Specialized Lists 183
PART III RECURSION AND QUICKSORT 205
Hour 11 Recursion 207
12 Applied Recursion 233
13 Quicksort 257
14 Improving Quicksort 279
PART IV TREES 295
Hour 15 Binary Trees 297
16 Traversing Binary Trees 317

17 Red-Black Trees 337
18 Red-Black Tree Insertions 359
19 2-3-4 Trees 379
20 Implementing 2-3-4 Trees 395
00 72316331 FM 10/31/02 6:54 AM Page iii
PART VHASH TABLES 415
Hour 21 Hash Tables 417
22 Quadratic Probing 441
23 Separate Chaining 457
24 When to Use What 475
PART VI APPENDIXES 487
Appendix A Quiz Answers 489
BHow to Run the Workshop Applets and Sample Programs 505
C Further Reading 509
Index 513
00 72316331 FM 10/31/02 6:54 AM Page iv
TeamLRN
Table of Contents
INTRODUCTION 1
What This Book Is About 1
What’s Different About This Book 2
Easy to Understand 2
Workshop Applets 2
C++ Sample Code 3
Who This Book Is For 3
What You Need to Know Before You Read This Book 4
The Software You Need to Use This Book 4
How This Book Is Organized 4
Enjoy Yourself! 6
Conventions Used in This Book 6

PART IINTRODUCING DATA STRUCTURES AND ALGORITHMS 9
HOUR 1OVERVIEW OF DATA STRUCTURES AND ALGORITHMS 11
Some Uses for Data Structures and Algorithms 12
Real-World Data Storage 12
Programmer’s Tools 14
Real-World Modeling 14
Overview of Data Structures 14
Overview of Algorithms 15
Some Initial Definitions 16
Datafile 16
Record 16
Field 16
Key 16
Search Key 17
A Quick Introduction to Object-Oriented Programming 18
Problems with Procedural Languages 18
Objects in a Nutshell 19
A Runnable Object-Oriented Program 21
Inheritance and Polymorphism 24
New C++ Features 25
The
string Class 25
The
vector Class 26
Software Engineering 26
Summary 27
00 72316331 FM 10/31/02 6:54 AM Page v
Q&A 28
Workshop 28
Quiz 28

Exercise 29
HOUR 2ARRAYS 31
The Array Workshop Applet 31
Deletion 34
The Duplicates Problem 35
Slow Array Algorithms 37
An Array Example 37
Inserting a New Item 39
Searching for an Item 39
Deleting an Item 39
Displaying the Array Contents 40
Program Organization 40
Dividing a Program into Classes 40
The
LowArray Class and main() 42
Class Interfaces 43
Making
main()’s Job Easier 43
Who’s Responsible for What? 44
The
highArray.cpp Example 44
The User’s Life Made Easier 48
Abstraction 48
Summary 48
Q&A 49
Workshop 49
Quiz 49
Exercise 50
HOUR 3ORDERED ARRAYS 51
The Ordered Workshop Applet 51

Demonstrating the Linear Search 52
Demonstrating the Binary Search 53
C++ Code for an Ordered Array 55
Conducting a Binary Search with the
find() Member Function 56
Investigating the
OrdArray Class 57
The Advantages of Using Ordered Arrays 60
Logarithms 61
An Equation Relating Range Size and Number of Steps 62
The Opposite of Raising Two to a Power 63
Storing Objects 64
vi Sams Teach Yourself Data Structures and Algorithms in 24 Hours
00 72316331 FM 10/31/02 6:54 AM Page vi
TeamLRN
Implementing the Person Class 64
Examining the
classDataArray.cpp Program 65
Big O Notation 69
Inserting into an Unordered Array: Constant 69
Linear Searching: Proportional to N 69
Binary Searching: Proportional to log(N) 70
Eliminating the Constant K 70
Why Not Use Arrays for Everything? 72
Summary 72
Q&A 72
Workshop 73
Quiz 73
Exercise 73
HOUR 4THE BUBBLE SORT 75

Sorting 75
Inventing Your Own Sorting Algorithm 76
Bubble-Sorting the Baseball Players 77
The bubbleSort Workshop Applet 79
Sorting at Full Speed with the Run Button 80
Starting a New Sort with the New Button 80
Single-Stepping with the Step Button 81
Changing the Array Size with the Size Button 81
Fixing the Picture with the Draw Button 82
Implementing C++ Code for a Bubble Sort 83
Invariants 86
Efficiency of the Bubble Sort 86
Summary 87
Q&A 87
Workshop 88
Quiz 88
Exercise 88
HOUR 5THE INSERTION SORT 89
Insertion Sort on the Baseball Players 90
Demonstrating Partial Sorting 90
Inserting the Marked Player in the Appropriate Location 90
The insertSort Workshop Applet 92
Implementing the Insertion Sort in C++ 94
Invariants in the Insertion Sort 97
Efficiency of the Insertion Sort 97
Sorting Objects 98
Implementing C++ Code to Sort Objects 98
Contents vii
00 72316331 FM 10/31/02 6:54 AM Page vii
Another Feature of Sorting Algorithms: Stability 101

Comparing the Simple Sorts 102
Summary 102
Q&A 103
Workshop 103
Quiz 103
Exercise 103
PART II ABSTRACT DATA TYPES 105
HOUR 6STACKS 107
A Different Way to Think About Data Structure 107
Uses for Stacks and Queues: Programmer’s Tools 108
Stacks and Queues: Restricted Access to Data 108
Stacks and Queues: More Abstract 108
Understanding Stacks 109
Two Real-World Stack Analogies 109
The Stack Workshop Applet 111
Implementing a Stack in C++ 113
StackX Class Member Functions 114
Error Handling 116
Stack Example 1: Reversing a Word 116
Stack Example 2: Delimiter Matching 118
Opening Delimiters on the Stack 119
C++ Code for
brackets.cpp 120
Using the Stack as a Conceptual Aid 123
Efficiency of Stacks 123
Summary 123
Q&A 124
Workshop 124
Quiz 124
Exercise 124

HOUR 7QUEUES AND PRIORITY QUEUES 125
Queues 125
The Queue Workshop Applet 126
A Circular Queue 130
C++ Code for a Queue 132
Efficiency of Queues 137
Priority Queues 137
The PriorityQ Workshop Applet 138
viii Sams Teach Yourself Data Structures and Algorithms in 24 Hours
00 72316331 FM 10/31/02 6:54 AM Page viii
TeamLRN
C++ Code for a Priority Queue 141
Efficiency of Priority Queues 143
Summary 143
Q&A 144
Workshop 144
Quiz 144
Exercise 144
HOUR 8LINKED LISTS 145
Understanding Links 146
Structure Defined by Relationship, Not Position 147
The LinkList Workshop Applet 147
Inserting a New Link 147
Using the Find Button 148
Using the Del Button 149
Creating Unsorted and Sorted Lists 149
Implementing a Simple Linked List 149
The
Link Class 150
The

LinkList Class 151
The
insertFirst() Member Function 151
The
removeFirst() Member Function 153
The
displayList() Member Function 153
The
linkList.cpp Program 155
Finding and Removing Specified Links 157
The
find() Member Function 160
The
remove() Member Function 161
Avoiding Memory Leaks 162
The Efficiency of Linked Lists 162
Summary 163
Q&A 163
Workshop 164
Quiz 164
Exercise 164
HOUR 9ABSTRACT DATA TYPES 165
A Stack Implemented By a Linked List 166
Implementing
push() and pop() 166
Implementing a Stack Based on a Linked List 167
Focusing on Class Relationships 170
Double-Ended Lists 170
Accessing Both Ends of a List 170
Implementing a Double-Ended List 171

Pointers to Both Ends of the List 174
Insertion and Deletion Routines 174
Contents ix
00 72316331 FM 10/31/02 6:54 AM Page ix
x Sams Teach Yourself Data Structures and Algorithms in 24 Hours
Implementing a Queue Using a Linked List 175
Data Types and Abstraction 178
What We Mean by
Data Types 178
What We Mean by
Abstraction 179
ADT Lists 180
Using ADTs as a Design Tool 180
Abstract is a Relative Term 181
Summary 181
Q&A 181
Workshop 182
Quiz 182
Exercise 182
HOUR 10 SPECIALIZED LISTS 183
Sorted Lists 183
The LinkList Workshop Applet 184
Implementing an Insertion Function in C++ 185
Implementing a Sorted List 186
Efficiency of Sorted Linked Lists 189
List Insertion Sort 189
Doubly Linked Lists 192
The Problem with Singly Linked Lists 192
Implementing a Doubly Linked List 193
C++ Code for a Doubly Linked List 197

Summary 202
Q&A 203
Workshop 203
Quiz 203
Exercise 203
PART III RECURSION AND QUICKSORT 205
HOUR 11 RECURSION 207
Demonstrating Recursion with Triangular Numbers 208
Finding the
nth Term Using a Loop 208
Finding the
nth Term Using Recursion 209
The
triangle.cpp Program 212
What the
triangle() Function Is Really Doing 213
Characteristics of Recursive Functions 215
Is Recursion Efficient? 215
Mathematical Induction 216
00 72316331 FM 10/31/02 6:54 AM Page x
TeamLRN
Contents xi
Demonstrating Recursion with Anagrams 216
Conceptualizing the Anagram Process 217
Implementing Anagramming in C++ 220
Demonstrating Recursion in a Binary Search 223
Using Recursion to Replace the Loop 223
Understanding Divide-and-Conquer Algorithms 228
Recursion Versus Stacks 228
Summary 230

Q&A 231
Workshop 231
Quiz 231
Exercise 232
HOUR 12 APPLIED RECURSION 233
The Towers of Hanoi 233
The Towers Workshop Applet 234
Moving Subtrees 235
The Recursive Algorithm 236
Implementing the Towers of Hanoi in C++ 238
Mergesort 240
Merging Two Sorted Arrays 240
Sorting by Merging 243
The mergeSort Workshop Applet 246
Implementing Mergesort in C++ 247
Efficiency of the Mergesort 251
Summary 254
Q&A 255
Workshop 255
Quiz 255
Exercise 256
HOUR 13 QUICKSORT 257
Partitioning 258
The Partition Workshop Applet 258
The
partition.cpp Program 260
The Partition Algorithm 262
Efficiency of the Partition Algorithm 264
Basic Quicksort 265
The Quicksort Algorithm 265

Choosing a Pivot Value 266
The quickSort1 Workshop Applet 272
Summary 277
00 72316331 FM 10/31/02 6:54 AM Page xi
Q&A 278
Workshop 278
Quiz 278
Exercise 278
HOUR 14 IMPROVING QUICKSORT 279
Problems with Inversely Sorted Data 279
Median-of-Three Partitioning 280
Implementing Median-of-Three Partitioning in C++ 282
The quickSort2 Workshop Applet 286
Handling Small Partitions 286
Using an Insertion Sort for Small Partitions 286
Insertion Sort Following Quicksort 290
Efficiency of Quicksort 290
Summary 293
Q&A 294
Workshop 294
Quiz 294
Exercise 294
PART IV TREES 295
HOUR 15 BINARY TREES 297
Why Use Binary Trees? 297
Slow Insertion in an Ordered Array 298
Slow Searching in a Linked List 298
Trees to the Rescue 299
What Is a Tree? 299
Tree Terminology 300

A Tree Analogy in Your Computer 303
Basic Binary Tree Operations 304
The Tree Workshop Applet 304
Representing the Tree in C++ Code 306
Finding a Node 308
Using the Workshop Applet to Find a Node 309
C++ Code for Finding a Node 310
Efficiency of the Find Operation 311
Inserting a Node 311
Using the Workshop Applet to Insert a Node 311
C++ Code for Inserting a Node 312
Deleting a Node 314
Summary 314
xii Sams Teach Yourself Data Structures and Algorithms in 24 Hours
00 72316331 FM 10/31/02 6:54 AM Page xii
TeamLRN
Q&A 315
Workshop 315
Quiz 315
Exercise 316
HOUR 16 TRAVERSING BINARY TREES 317
Traversing the Tree 317
Inorder Traversal 318
C++ Code for Traversing 318
Traversing a 3-Node Tree 319
Traversing with the Workshop Applet 320
Preorder and Postorder Traversals 322
Finding Maximum and Minimum Values 324
The Efficiency of Binary Trees 326
Duplicate Keys 327

Implementing a Binary Search Tree in C++ 328
Summary 335
Q&A 335
Workshop 335
Quiz 336
Exercise 336
HOUR 17 RED-BLACK TREES 337
Our Approach to the Discussion 338
Balanced and Unbalanced Trees 338
Performance Degenerates to O(N) 339
Balanced Trees to the Rescue 340
Red-Black Tree Characteristics 341
The Actions 342
Using the RBTree Workshop Applet 343
Clicking on a Node 343
The Start Button 343
The Ins Button 344
The Del Button 344
The Flip Button 344
The RoL Button 344
The RoR Button 345
The R/B Button 345
Text Messages 345
Where’s the Find Button? 345
Experimenting 345
Experiment 1: Simple Insertions 345
Experiment 2: Rotations 347
Contents xiii
00 72316331 FM 10/31/02 6:54 AM Page xiii
Experiment 3: Color Flips 348

Experiment 4: An Unbalanced Tree 349
Experimenting on Your Own 350
The Red-Black Rules and Balanced Trees 350
Null Children 350
Rotations 351
Simple Rotations 352
The Weird Crossover Node 352
Subtrees on the Move 354
Human Beings Versus Computers 355
Summary 356
Q&A 356
Workshop 357
Quiz 357
Exercise 357
HOUR 18 RED-BLACK TREE INSERTIONS 359
Inserting a New Node 360
Preview of Our Approach 360
Color Flips on the Way Down 361
Rotations After the Node Is Inserted 363
Rotations on the Way Down 370
Deletion 373
Efficiency of Red-Black Trees 374
Implementing the Insertion Process 374
Other Balanced Trees 375
AVL Trees 375
Multiway Trees 375
Summary 376
Q&A 376
Workshop 376
Quiz 377

Exercise 377
HOUR 19 2-3-4 TREES 379
Introduction to 2-3-4 Trees 379
What’s in a Name? 380
2-3-4 Tree Organization 381
Searching for a Data Item 383
Inserting a New Data Item 383
Node Splits 384
Splitting the Root 385
Splitting Nodes on the Way Down 386
xiv Sams Teach Yourself Data Structures and Algorithms in 24 Hours
00 72316331 FM 10/31/02 6:54 AM Page xiv
TeamLRN
The Tree234 Workshop Applet 387
The Fill Button 388
The Find Button 388
The Ins Button 389
The Zoom Button 389
Viewing Different Nodes 390
Experimenting on Your Own 392
Summary 392
Q&A 393
Workshop 393
Quiz 393
Exercise 394
HOUR 20 IMPLEMENTING 2-3-4 TREES 395
Implementing a 2-3-4 Tree in C++ 395
The
DataItem Class 396
The

Node Class 396
The
Tree234 Class 396
The
main() Function 398
Listing for
tree234.cpp 398
2-3-4 Trees and Red-Black Trees 405
Transformation from 2-3-4 to Red-Black 406
Operational Equivalence 406
Efficiency of 2-3-4 Trees 409
Speed 410
Storage Requirements 411
B-Trees and External Storage 412
Summary 412
Q&A 413
Workshop 413
Quiz 413
Exercise 414
PART VHASH TABLES 415
HOUR 21 HASH TABLES 417
Introduction to Hashing 417
Employee Numbers as Keys 418
A Dictionary 420
Hashing 423
Collisions 426
Contents xv
00 72316331 FM 10/31/02 6:54 AM Page xv
Linear Probing 427
The Hash Workshop Applet 427

Duplicates Allowed? 432
Clustering 432
C++ Code for a Linear Probe Hash Table 432
Classes in
hash.cpp 436
The
find() Member Function 436
The
insert() Member Function 437
The
remove() Member Function 437
The
main() Routine 437
Summary 438
Q&A 439
Workshop 439
Quiz 439
Exercise 439
HOUR 22 QUADRATIC PROBING 441
Quadratic Probing 442
The Step Is the Square of the Step Number 442
The HashDouble Applet with Quadratic Probes 442
The Problem with Quadratic Probes 444
Double Hashing 444
The HashDouble Applet with Double Hashing 445
C++ Code for Double Hashing 446
Make the Table Size a Prime Number 451
Efficiency of Open Addressing 451
Linear Probing 452
Quadratic Probing and Double Hashing 452

Expanding the Array 454
Summary 455
Q&A 455
Workshop 456
Quiz 456
Exercise 456
HOUR 23 SEPARATE CHAINING 457
The HashChain Workshop Applet 458
Insertion 459
Load Factors 460
Duplicates 460
Deletion 460
Table Size 461
Buckets 461
xvi Sams Teach Yourself Data Structures and Algorithms in 24 Hours
00 72316331 FM 10/31/02 6:54 AM Page xvi
TeamLRN
C++ Code for Separate Chaining 461
Efficiency of Separate Chaining 466
Searching 467
Insertion 467
Open Addressing Versus Separate Chaining 468
Hash Functions 469
Quick Computation 469
Random Keys 469
Non-Random Keys 469
Hashing Strings 471
Summary 473
Q&A 474
Workshop 474

Quiz 474
Exercise 474
HOUR 24 WHEN TO USE WHAT 475
General-Purpose Data Structures 476
Speed and Algorithms 477
Libraries 478
Arrays 478
Linked Lists 478
Binary Search Trees 479
Balanced Trees 479
Hash Tables 479
Comparing the General-Purpose Storage Structures 480
Special-Purpose Data Structures 481
Stack 481
Queue 482
Priority Queue 482
Comparison of Special-Purpose Structures 483
Sorting 483
Onward 484
PART VI APPENDIXES 487
APPENDIX AQUIZ ANSWERS 489
Hour 1, “Overview of Data Structures and Algorithms” 489
Hour 2, “Arrays” 490
Hour 3, “Ordered Arrays” 490
Hour 4, “The Bubble Sort” 491
Hour 5, “The Insertion Sort” 492
Contents xvii
00 72316331 FM 10/31/02 6:54 AM Page xvii
Hour 6, “Stacks” 492
Hour 7, “Queues and Priority Queues” 493

Hour 8, “Linked Lists” 494
Hour 9, “Abstract Data Types” 494
Hour 10, “Specialized Lists” 495
Hour 11, “Recursion” 496
Hour 12, “Applied Recursion” 496
Hour 13, “Quicksort” 497
Hour 14, “Improving Quicksort” 498
Hour 15, “Binary Trees” 498
Hour 16, “Traversing Binary Trees” 499
Hour 17, “Red-Black Trees” 500
Hour 18, “Red-Black Tree Insertions” 500
Hour 19, “2-3-4 Trees” 501
Hour 20, “Implementing 2-3-4 Trees” 502
Hour 21, “Hash Tables” 503
Hour 22, “Quadratic Probing” 503
Hour 23, “Separate Chaining” 504
APPENDIX BHOW TO RUN THE WORKSHOP APPLETS AND SAMPLE PROGRAMS 505
The Workshop Applets 506
Opening the Workshop Applets 506
Operating the Workshop Applets 506
Multiple Class Files 507
The Sample Programs 507
Running the Sample Programs 508
Compiling the Sample Programs 508
Terminating the Sample Programs 508
APPENDIX CFURTHER READING 509
Data Structures and Algorithms 509
Object-Oriented Programming Languages 510
Object-Oriented Design and Software Engineering 511
Programming Style 512

INDEX 513
xviii Sams Teach Yourself Data Structures and Algorithms in 24 Hours
00 72316331 FM 10/31/02 6:54 AM Page xviii
TeamLRN
About the Author
Robert Lafore has degrees in Electrical Engineering and Mathematics, has worked as a
systems analyst for the Lawrence Berkeley Laboratory, founded his own software com-
pany, and is a best-selling writer in the field of computer programming. Some of his cur-
rent titles are C++ Interactive Course, Object-Oriented Programming in C++, and Data
Structures and Algorithms in Java by all Waite Group Press. Earlier best-selling titles
include Assembly Language Primer for the IBM PC and (back at the beginning of the
computer revolution) Soul of CP/M.
00 72316331 FM 10/31/02 6:54 AM Page xix
Dedication
This book is dedicated to Laurie Cameron, a friend since the Paleolithic era,
and our English teacher Mrs. Mathews. Rule 22! Semicolons separate independent clauses!
Acknowledgments
My primary thanks go to my executive editor at Sams Publishing, Brian Gill, who con-
ceived this book idea and ably shepherded it to completion. My development editor, Jeff
Durham, performed his usual masterful job of expunging inconsistencies, lacunae, and
downright blunders while readying the manuscript for production. Tonya Simpson, the
project editor, did a masterful job of making sure that everyone else's work fit together
into a coherent whole. Mike Henry handled the copy editing very professionally, ensur-
ing that may was always might. Richard Wright, the tech editor, went through everything
with a fine-tooth comb and caught a few whoppers that one else could have. Dan Scherf
put the CD together in his usual competent way. My thanks to you all.
00 72316331 FM 10/31/02 6:54 AM Page xx
TeamLRN
Tell Us What You Think!
As the reader of this book, you are our most important critic and commentator. We value

your opinion and want to know what we’re doing right, what we could do better, what
areas you’d like to see us publish in, and any other words of wisdom you’re willing to
pass our way.
As an Associate Publisher for Sams Publishing, I welcome your comments. You can fax,
email, or write me directly to let me know what you did or didn’t like about this book—
as well as what we can do to make our books stronger.
Please note that I cannot help you with technical problems related to the topic of this
book, and that due to the high volume of mail I receive, I might not be able to reply to
every message.
When you write, please be sure to include this book’s title and author as well as your
name and phone or fax number. I will carefully review your comments and share them
with the author and editors who worked on the book.
Fax: 317-581-4770
Email:
Mail: Bradley L. Jones
Associate Publisher
Sams Publishing
201 West 103rd Street
Indianapolis, IN 46290 USA
00 72316331 FM 10/31/02 6:54 AM Page xxi
00 72316331 FM 10/31/02 6:54 AM Page xxii
TeamLRN
Introduction
This introduction tells you briefly

What this book is about

Why it’s different

Who might want to read it


What you need to know before you read it

The software and equipment you need to use it

How this book is organized
What This Book Is About
This book is about data structures and algorithms as used in computer programming.
Data structures are ways in which data is arranged in your computer’s memory (or stored
on disk). Algorithms are the procedures a software program uses to manipulate the data
in these structures.
Almost every computer program, even a simple one, uses data structures and algorithms.
For example, consider a program that prints address labels. The program might use an
array containing the addresses to be printed, and a simple for loop to step through the
array, printing each address.
The array in this example is a data structure, and the
for loop, used for sequential access
to the array, executes a simple algorithm. For uncomplicated programs with small
amounts of data, such a simple approach might be all you need. However, for programs
that handle even moderately large amounts of data, or which solve problems that are
slightly out of the ordinary, more sophisticated techniques are necessary. Simply know-
ing the syntax of a computer language such as C++ isn’t enough.
This book is about what you need to know after you’ve learned a programming lan-
guage. The material we cover here is typically taught in colleges and universities as a
second-year course in computer science, after a student has mastered the fundamentals of
programming.
01 72316331 Intro 10/31/02 6:54 AM Page 1
2 Sams Teach Yourself Data Structures and Algorithms in 24 Hours
What’s Different About This Book
There are dozens of books on data structures and algorithms. What’s different about this

one? Three things:

Our primary goal in writing this book is to make the topics we cover easy to under-
stand.

Demonstration programs called Workshop applets bring to life the topics we cover,
showing you step by step, with “moving pictures,” how data structures and algo-
rithms work.

The sample code is written as clearly and concisely as possible, using C++.
Let’s look at these features in more detail.
Easy to Understand
Typical computer science textbooks are full of theory, mathematical formulas, and
abstruse examples of computer code. This book, on the other hand, concentrates on sim-
ple explanations of techniques that can be applied to real-world problems. We avoid
complex proofs and heavy math. There are lots of figures to augment the text.
Many books on data structures and algorithms include considerable material on software
engineering. Software engineering is a body of study concerned with designing and
implementing large and complex software projects.
However, it’s our belief that data structures and algorithms are complicated enough with-
out involving this additional discipline, so we have deliberately de-emphasized software
engineering in this book. (We’ll discuss the relationship of data structures and algorithms
to software engineering in Hour 1, “Overview of Data Structures and Alogorithms.”)
Of course we use an object-oriented approach, and we discuss various aspects of object-
oriented design as we go along, including a mini-tutorial on OOP in Hour 1. Our primary
emphasis, however, is on the data structures and algorithms themselves.
Workshop Applets
The CD-ROM that accompanies this book includes demonstration programs, in the form
of Java applets, that cover the topics we discuss. These applets, which we call Workshop
applets, will run on most computer systems, using a Web browser. A Web browser for

Microsoft Windows systems is included with the CD-ROM that accompanies this book.
(See the readme file on the CD-ROM for more details on software compatibility.)
01 72316331 Intro 10/31/02 6:54 AM Page 2
TeamLRN

×