Java Software Structures Designing And Using
Data Structures 3rd Edition John Lewis download
https://ebookbell.com/product/java-software-structures-designing-
and-using-data-structures-3rd-edition-john-lewis-2614256
Explore and download more ebooks at ebookbell.com
Here are some recommended products that we believe you will be
interested in. You can click the link to download.
Java Software Structures Designing And Using Data Structures 4th
Edition International Edition Lewis
https://ebookbell.com/product/java-software-structures-designing-and-
using-data-structures-4th-edition-international-edition-lewis-21976872
Java 19 More Algorithms And Data Structures Software Development Poul
Klausen
https://ebookbell.com/product/java-19-more-algorithms-and-data-
structures-software-development-poul-klausen-47502928
Java 18 Algorithms And Data Structures Software Development No Isbn
Poul Klausen
https://ebookbell.com/product/java-18-algorithms-and-data-structures-
software-development-no-isbn-poul-klausen-47502932
Java Software And Embedded Systems 1st Edition Mattis Hayes Isaiah
Johansen
https://ebookbell.com/product/java-software-and-embedded-systems-1st-
edition-mattis-hayes-isaiah-johansen-51764284
Java Software Solutions For Ap Computer Science 3rd Edition Loftus
https://ebookbell.com/product/java-software-solutions-for-ap-computer-
science-3rd-edition-loftus-21354562
Java Software Solutions Foundations Of Program Design 7th Edition 7th
Edition John Lewis
https://ebookbell.com/product/java-software-solutions-foundations-of-
program-design-7th-edition-7th-edition-john-lewis-2371348
Java Software Solutions Global Edition 8th Edition John Lewis
https://ebookbell.com/product/java-software-solutions-global-
edition-8th-edition-john-lewis-30066712
Java Software Solutions 9th Edition John Lewis William Loftus
https://ebookbell.com/product/java-software-solutions-9th-edition-
john-lewis-william-loftus-33941204
Java Software Solutions 8th Edition 8th Edition Lewis John
https://ebookbell.com/product/java-software-solutions-8th-edition-8th-
edition-lewis-john-55557960
java
S O F T WA R E S T R U C T U R E S
Third Edition
™
Designing and Using Data Structures
This page intentionally left blank
java
S O F T WA R E S T R U C T U R E S
Third Edition
Designing and Using Data Structures
Addison-Wesley
New York Boston San Francisco
London Toronto Sydney Tokyo Singapore Madrid
Mexico City Munich Paris Cape Town Hong Kong Montreal
JOHN LEWIS
Virginia Tech
JOSEPH CHASE
Radford University
™
Editor-in-Chief Michael Hirsch
Editorial Assistant Stephanie Sellinger
Managing Editor Jeffrey Holcomb
Production Supervisor Heather McNally
Marketing Manager Erin Davis
Marketing Coordinator Kathryn Ferranti
Senior Manufacturing Buyer Carol Melville
Online Product Manager Bethany Tidd
Art Director Linda Knowles
Cover Design Elena Sidorova
Project Management, Composition, and Illustrations Nesbitt Graphics, Inc.
Project Coordinator, Nesbitt Graphics, Inc. Harry Druding
Project Manager, Nesbitt Graphics, Inc. Kathy Smith
Text Design, Nesbitt Graphics, Inc. Jerilyn Bockorick, Alisha Webber
Cover Image Steve Cole/Getty Images
Access the latest information about Addison-Wesley Computer Science titles from our World Wide Web site:
http://www.pearsonhighered.com/cs.
Many of the designations used by manufacturers and sellers to distinguish their products are claimed as trademarks. Where those
designations appear in this book, and Addison-Wesley was aware of a trademark claim, the designations have been printed in
initial caps or all caps.
The programs and applications presented in this book have been included for their instructional value. They have been tested
with care, but are not guaranteed for any particular purpose. The publisher does not offer any warranties or representations,
nor does it accept any liabilities with respect to the programs or applications.
Library of Congress Cataloging-in-Publication Data
Lewis, John, 1963-
Java software structures : designing and using data structures / John
Lewis, Joseph Chase. -- 3rd ed.
p. cm.
Includes bibliographical references and index.
ISBN 978-0-13-607858-6 (alk. paper)
1. Java (Computer program language) 2. Data structures (Computer science)
3. Computer software--Development. I. Chase, Joseph. II. Title.
QA76.73.J38L493 2009
005.13'3--dc22
2009000302
Copyright © 2010 Pearson Education, Inc. All rights reserved. No part of this publication may be reproduced, stored in a
retrieval system, or transmitted, in any form or by any means, electronic, mechanical, photocopying, recording, or otherwise,
without the prior written permission of the publisher. Printed in the United States of America.
For information on obtaining permission for use of material in this work, please submit a written request to Pearson
Education, Inc., Rights and Contracts Department, 501 Boylston Street, Suite 900, Boston, MA 02116, fax your request to
(617)671-3447, or e-mail at http://www.pearsoned.com/legal/permissions.htm.
Addison Wesley
is an imprint of
www.pearsonhighered.com
ISBN-13: 978-013-607858-6
ISBN-10: 0-13-607858-3
1 2 3 4 5 6 7 8 10–EB–13 12 11 10 09
To my wife Sharon and my kids:
Justin, Kayla, Nathan, and Samantha
–J. L.
To my loving wife Melissa for her support and encouragement
and to our families, friends, colleagues, and students who have provided
so much support and inspiration through the years.
–J. C.
This page intentionally left blank
Preface
vii
This book is designed to serve as a text for a course on data structures and algo-
rithms. This course is typically referred to as the CS2 course because it is often
taken as the second course in a computing curriculum. We have designed this
book to embrace the tenets of Computing Curricula 2001 (CC2001).
Pedagogically, this book follows the style and approach of the leading CS1
book Java Software Solutions: Foundations of Program Design, by John Lewis
and William Loftus. Our book uses many of the highly regarded features of that
book, such as the Key Concept boxes and complete code examples. Together,
these two books support a solid and consistent approach to either a two-course
or three-course introductory sequence for computing students. That said, this
book does not assume that students have used Java Software Solutions in a previ-
ous course.
Material that might be presented in either course (such as recursion or sorting)
is presented in this book as well. We also include strong reference material pro-
viding an overview of object-oriented concepts and how they are realized in Java.
We understand the crucial role that the data structures and algorithms course
plays in a curriculum and we think this book serves the needs of that course well.
The Third Edition
We have made some key modifications in this third edition to enhance its peda-
gogy. The most important change is a fundamental reorganization of material that
is designed to create a cleaner flow of topics. Instead of having an early, large
chapter to review object-oriented concepts, we’ve included that material as an
appendix for reference. Then we review concepts as needed and appropriate in the
context of the implementation strategies discussed throughout the book and cite
the appropriate reference material. This not only links the topics in a timely fash-
ion but also demonstrates the usefulness of particular language constructs.
We’ve expanded the discussion of Analysis of Algorithms, and given it its own
chapter. The discussion, however, stays at an appropriately moderate level. Our
strategy is to motivate the concepts involved in the analysis of algorithms, laying
a solid foundation, rather than get embroiled in too much formality.
Another key organizational change is that the introduction to collections uses
a stack as the primary example. In previous editions of this book we went out of
viii PREFACE
our way to introduce collections in an abstract way that separated it from the core
data structures, using examples such as a bag or set collection. This new approach
capitalizes on the fact that a stack is conceptually about as straightforward as it
gets. Using it as a first example enhances the understanding of collections as a
whole.
The previous edition of the book had several chapters that focused on larger
case studies that made use of collections to solve non-trivial problems. While
many instructors found these useful, they also seemed to interrupt the flow of cov-
erage of core topics. Therefore we have taken the case study chapters out of the
book and put them on the web as supplementary resources. We encourage all
instructors to download and use these resources as they see fit.
Finally, for this edition we’ve reviewed and improved the discussions through-
out the book. We’ve expanded the discussion of graphs and reversed the order of
the graphs and hashing chapters to make a cleaner flow. And we’ve added a chap-
ter that specifically covers sets and maps.
We think these modifications build upon the strong pedagogy established by
previous editions and give instructors more opportunity and flexibility to cover
topics as they choose.
Our Approach
Books of this type vary greatly in their overall approach. Our approach is founded
on a few important principles that we fervently embraced. First, we present the
various collections explored in the book in a consistent manner. Second, we
emphasize the importance of sound software design techniques. Third, we organ-
ized the book to support and reinforce the big picture: the study of data structures
and algorithms. Let’s examine these principles further.
Consistent Presentation
When exploring a particular type of collection, we carefully address each of the
following issues in order:
1. Concept: We discuss the collection conceptually, establishing the services it
provides (its interface).
2. Use: We explore examples that illustrate how the particular nature of the
collection, no matter how it’s implemented, can be useful when solving
problems.
3. Implementation: We explore various implementation options for the
collection.
4. Analysis: We compare and contrast the implementations.
PREFACE ix
The Java Collections API is included in the discussion as appropriate. If there
is support for a particular collection type in the API, we discuss it and its imple-
mentation. Thus we embrace the API, but are not completely tied to it. And we
are not hesitant to point out its shortcomings.
The analysis is kept at a high level. We establish the concept of Big-Oh nota-
tion in Chapter 2 and use it throughout the book, but the analysis is more intu-
itive than it is mathematical.
Sound Program Design
Throughout the book, we keep sound software engineering practices a high pri-
ority. Our design of collection implementations and the programs that use them
follow consistent and appropriate standards.
Of primary importance is the separation of a collection’s interface from its under-
lying implementation. The services that a collection provides are always formally
defined in a Java interface. The interface name is used as the type designation of the
collection whenever appropriate to reinforce the collection as an abstraction.
In addition to practicing solid design principles, we stress them in the discus-
sion throughout the text. We attempt to teach both by example and by continual
reinforcement.
Clean Organization
The contents of the book have been carefully organized to minimize distracting
tangents and to reinforce the overall purpose of the book. The organization sup-
ports the book in its role as a pedagogical exploration of data structures and algo-
rithms as well as its role as a valuable reference.
The book can be divided into numerous parts: Part I consists of the first two
chapters and provides an introduction to the concept of a collection and analysis
of algorithms. Part II includes the next four chapters, which cover introductory
and underlying issues that affect all aspects of data structures and algorithms as
well as linear collections (stacks, queues, and lists). Part III covers the concepts of
recursion, sorting, and searching. Part IV covers the nonlinear collections (trees,
heaps, hashing, and graphs). Each type of collection, with the exception of trees,
is covered in its own chapter. Trees are covered in a series of chapters that explore
their various aspects and purposes.
Chapter Breakdown
Chapter 1 (Introduction) discusses various aspects of software quality and pro-
vides an overview of software development issues. It is designed to establish the
x PREFACE
appropriate mindset before embarking on the details of data structure and algo-
rithm design.
Chapter 2 (Analysis of Algorithms) lays the foundation for determining the
efficiency of an algorithm and explains the important criteria that allow a devel-
oper to compare one algorithm to another in proper ways. Our emphasis in this
chapter is understanding the important concepts more than getting mired in heavy
math or formality.
Chapter 3 (Collections) establishes the concept of a collection, stressing the
need to separate the interface from the implementation. It also conceptually intro-
duces a stack, then explores an array-based implementation of a stack.
Chapter 4 (Linked Structures) discusses the use of references to create linked
data structures. It explores the basic issues regarding the management of linked
lists, and then defines an alternative implementation of a stack (introduced in
Chapter 3) using an underlying linked data structure.
Chapter 5 (Queues) explores the concept and implementation of a first-in, first-
out queue. Radix sort is discussed as an example of using queues effectively. The
implementation options covered include an underlying linked list as well as both
fixed and circular arrays.
Chapter 6 (Lists) covers three types of lists: ordered, unordered, and indexed.
These three types of lists are compared and contrasted, with discussion of the
operations that they share and those that are unique to each type. Inheritance is
used appropriately in the design of the various types of lists, which are imple-
mented using both array-based and linked representations.
Chapter 7 (Recursion) is a general introduction to the concept of recursion and
how recursive solutions can be elegant. It explores the implementation details of
recursion and discusses the basic idea of analyzing recursive algorithms.
Chapter 8 (Sorting and Searching) discusses the linear and binary search algo-
rithms, as well as the algorithms for several sorts: selection sort, insertion sort,
bubble sort, quick sort, and merge sort. Programming issues related to searching
and sorting, such as using the Comparable interface as the basis of comparing
objects, are stressed in this chapter. Searching and sorting that are based in par-
ticular data structures (such as heap sort) are covered in the appropriate chapter
later in the book.
Chapter 9 (Trees) provides an overview of trees, establishing key terminology
and concepts. It discusses various implementation approaches and uses a binary
tree to represent and evaluate an arithmetic expression.
Chapter 10 (Binary Search Trees) builds off of the basic concepts established in
Chapter 9 to define a classic binary search tree. A linked implementation of a
binary search tree is examined, followed by a discussion of how the balance in the
PREFACE xi
tree nodes is key to its performance. That leads to exploring AVL and red/black
implementations of binary search trees.
Chapter 11 (Priority Queues and Heaps) explores the concept, use, and imple-
mentations of heaps and specifically their relationship to priority queues. A heap
sort is used as an example of its usefulness as well. Both linked and array-based
implementations are explored.
Chapter 12 (Multi-way Search Trees) is a natural extension of the discussion of
the previous chapters. The concepts of 2-3 trees, 2-4 trees, and general B-trees are
examined and implementation options are discussed.
Chapter 13 (Graphs) explores the concept of undirected and directed graphs
and establishes important terminology. It examines several common graph algo-
rithms and discusses implementation options, including adjacency matrices.
Chapter 14 (Hashing) covers the concept of hashing and related issues, such as
hash functions and collisions. Various Java Collections API options for hashing
are discussed.
Chapter 15 (Sets and Maps) explores these two types of collections and their
importance to the Java Collections API.
Appendix A (UML) provides an introduction to the Unified Modeling
Language as a reference. UML is the de facto standard notation for representing
object-oriented systems.
Appendix B (Object-Oriented Design) is a reference for anyone needing a
review of fundamental object-oriented concepts and how they are accomplished
in Java. Included are the concepts of abstraction, classes, encapsulation, inheri-
tance, and polymorphism, as well as many related Java language constructs such
as interfaces.
Supplements
The following supplements are available to all readers of this book at www.aw
.com/cssupport.
■ Source Code for all programs presented in the book
■ Full case studies of programs that illustrate concepts from the text, includ-
ing a Black Jack Game, a Calculator, a Family Tree Program, and a Web
Crawler
The following instructor supplements are only available to qualified in-
structors at Pearson Education’s Instructor Resource Center, http://www
.pearsonhighered.com/irc. Please visit the Web site, contact your local Pearson
Education Sales Representative, or send an e-mail to computing@pearson.com,
for information about how to access them.
xii PREFACE
■ Solutions for selected exercises and programming projects in the book
■ Test Bank, containing questions that can be used for exams
■ PowerPoint® Slides for the presentation of the book content
Acknowledgements
First and most importantly we want to thank our students for whom this book is
written and without whom it never could have been. Your feedback helps us
become better educators and writers. Please continue to keep us on our toes.
We would like to thank all of the reviewers listed below who took the time to
share their insight on the content and presentation of the material in this book and
its previous editions. Your input was invaluable.
Mary P. Boelk, Marquette University
Robert Burton, Brigham Young University
Gerald Cohen, St. Joseph’s College
Robert Cohen, University of Massachusetts–Boston
Jack Davis, Radford University
Bob Holloway, University of Wisconsin–Madison
Nisar Hundewale, Georgia State University
Chung Lee, California State Polytechnic University
Mark C. Lewis, Trinity University
Mark J. Llewellyn, University of Central Florida
Ronald Marsh, University of North Dakota
Eli C. Minkoff, Bates College; University of Maine–Augusta
Ned Okie, Radford University
Manuel A. Perez-Quinones, Virginia Tech
Moshe Rosenfeld University of Washington
Salam Salloum, California State Polytechnic University–Pomona
Don Slater, Carnegie Mellon University
Ashish Soni, University of Southern California
Carola Wenk, University of Texas–San Antonio
The folks at Addison-Wesley have gone to great lengths to support and
develop this book along with us. It is a true team effort. Editor-in-Chief Michael
Hirsch and his assistant Stephanie Sellinger have always been there to help.
Marketing Manager Erin Davis, her assistant Kathryn Ferranti, and the entire
Addison-Wesley sales force work tirelessly to make sure that instructors under-
stand the goals and benefits of the book. Heather McNally flawlessly handled
the production of the book, and Elena Sidorova is to be credited for the won-
derful cover design. They are supported by Kathy Smith and Harry Druding at
Nesbitt Graphics. Carol Melville always finds a way to get us time on press so
PREFACE xiii
that our book makes it into your hands in time to use it in class. Thank you all
very much for all your hard work and dedication to this book.
We’d be remiss if we didn’t acknowledge the wonderful contributions of the
ACM Special Interest Group on Computer Science Education. Its publications and
conferences are crucial to anyone who takes the pedagogy of computing seriously.
If you’re not part of this group, you’re missing out.
Finally, we want to thank our families, who support and encourage us in what-
ever projects we find ourselves diving into. Ultimately, you are the reason we do
what we do.
This page intentionally left blank
Contents
xv
Preface
Chapter 1 Introduction 1
1.1 Software Quality 2
Correctness 3
Reliability 3
Robustness 4
Usability 4
Maintainability 5
Reusability 5
Portability 6
Efficiency 6
Quality Issues 6
1.2 Data Structures 7
A Physical Example 7
Containers as Objects 10
Chapter 2 Analysis of Algorithms 13
2.1 Algorithm Efficiency 14
2.2 Growth Functions and Big-OH Notation 15
2.3 Comparing Growth Functions 17
2.4 Determining Time Complexity 19
Analyzing Loop Execution 19
Nested Loops 20
Method Calls 21
Chapter 3 Collections 27
3.1 Introduction to Collections 28
Abstract Data Types 29
The Java Collections API 31
xvi CONTENTS
3.2 A Stack Collection 31
3.3 Crucial OO Concepts 33
Inheritance 34
Class Hierarchies 36
The Object Class 37
Polymorphism 38
References and Class Hierarchies 38
Generics 40
3.4 A Stack ADT 41
Interfaces 41
3.5 Using Stacks: Evaluating Postfix Expressions 44
3.6 Exceptions 51
Exception Messages 52
The try Statement 53
Exception Propagation 54
3.7 Implementing a Stack: With Arrays 55
Managing Capacity 56
3.8 The ArrayStack Class 57
The Constructors 58
The push Operation 59
The pop Operation 61
The peek Operation 62
Other Operations 63
Chapter 4 Linked Structures 71
4.1 References as Links 72
4.2 Managing Linked Lists 74
Accessing Elements 74
Inserting Nodes 75
Deleting Nodes 76
Sentinel Nodes 77
4.3 Elements Without Links 78
Doubly Linked Lists 78
4.4 Implementing a Stack: With Links 79
The LinkedStack Class 79
CONTENTS xvii
The push Operation 83
The pop Operation 85
Other Operations 86
4.5 Using Stacks: Traversing a Maze 86
4.6 Implementing Stacks:
The java.util.Stack Class 93
Unique Operations 93
Inheritance and Implementation 94
Chapter 5 Queues 99
5.1 A Queue ADT 100
5.2 Using Queues: Code Keys 103
5.3 Using Queues: Ticket Counter Simulation 107
5.4 Implementing Queues: With Links 112
The enque Operation 114
The dequeue Operation 115
Other Operations 117
5.5 Implementing Queues: With Arrays 117
The enqueue Operation 123
The dequeue Operation 124
Other Operations 125
Chapter 6 Lists 131
6.1 A List ADT 132
Iterators 134
Adding Elements to a List 135
Interfaces and Polymorphism 137
6.2 Using Ordered Lists: Tournament Maker 140
6.3 Using Indexed Lists: The Josephus Problem 150
6.4 Implementing Lists: With Arrays 152
The remove Operation 155
The contains Operation 157
The iterator Operation 158
The add Operation for an Ordered List 158
xviii CONTENTS
Operations Particular to Unordered Lists 161
The addAfter Operation for an Unordered List 162
6.5 Implementing Lists: With Links 163
The remove Operation 163
Doubly Linked Lists 165
The iterator Operation 168
6.6 Lists in the Java Collections API 171
Cloneable 172
Serializable 172
RandomAccess 172
Java.util.Vector 173
Java.util.ArrayList 173
Java.util.LinkedList 176
Chapter 7 Recursion 185
7.1 Recursive Thinking 186
Infinite Recursion 186
Recursion in Math 187
7.2 Recursive Programming 188
Recursion versus Iteration 190
Direct versus Indirect Recursion 191
7.3 Using Recursion 192
Traversing a Maze 192
The Towers of Hanoi 197
7.4 Analyzing Recursive Algorithms 201
Chapter 8 Sorting and Searching 209
8.1 Searching 210
Static Methods 211
Generic Methods 211
Linear Search 212
Binary Search 213
Comparing Search Algorithms 216
8.2 Sorting 217
Selection Sort 220
Insertion Sort 222
CONTENTS xix
Bubble Sort 224
Quick Sort 226
Merge Sort 229
8.3 Radix Sort 231
Chapter 9 Trees 241
9.1 Trees 242
Tree Classifications 243
9.2 Strategies for Implementing Trees 245
Computational Strategy for
Array Implementation of Trees 245
Simulated Link Strategy for
Array Implementation of Trees 246
Analtsis of Trees 247
9.3 Tree Traversals 248
Preorder Traversal 248
Inorder Traversal 249
Postorder Traversal 249
Level-Order Traversal 250
9.4 A Binary Tree ADT 251
9.5 Using Binary Trees: Expression Trees 255
9.6 Implementing Binary Trees with Links 262
The find Method 269
The iteratorInOrder Method 270
9.7 Implementing Binary Trees with Arrays 271
The find Method 273
The iteratorInOrder Method 274
Chapter 10 Binary Search Trees 281
10.1 A Binary Search Tree 282
10.2 Implementing Binary Search Trees:
With Links 284
The addElement Operation 286
The removeElement Operation 288
xx CONTENTS
The removeAllOccurrences Operation 291
The removeMin Operation 292
10.3 Implementing Binary Search Trees:
With Arrays 294
The addElement Operation 295
The removeElement Operation 296
The removeAllOccurrences Operation 302
The removeMin Operation 303
10.4 Using Binary Search Trees:
Implementing Ordered Lists 304
Analysis of the BinarySearchTreeList
Implementation 308
10.5 Balanced Binary Search Trees 309
Right Rotation 310
Left Rotation 310
Rightleft Rotation 311
Leftright Rotation 311
10.6 Implementing Binary Search Trees:
AVL Trees 312
Right Rotation in an AVL Tree 313
Left Rotation in an AVL Tree 315
Rightleft Rotation in an AVL Tree 315
Leftright Rotation in an AVL Tree 315
10.7 Implementing Binary Search Trees:
Red/Black Trees 315
Insertion into a Red/Black Tree 316
Element Removal from a Red/Black Tree 319
10.8 Implementing Binary Search Trees:
The Java Collections API 321
10.9 A Philosophical Quandary 325
Chapter 11 Priority Queues and Heaps 333
11.1 A Heap 334
The addElement Operation 334
The removeMin Operation 337
The findMin Operation 338
11.2 Using Heaps: Priority Queues 339
CONTENTS xxi
11.3 Implementing Heaps: With Links 343
The addElement Operation 343
The removeMin Operation 346
The findMin Operation 349
11.4 Implementing Heaps: With Arrays 350
The addElement Operation 350
The removeMin Operation 352
The findMin Operation 353
11.5 Using Heaps: Heap Sort 354
Chapter 12 Multi-way Search Trees 361
12.1 Combining Tree Concepts 362
12.2 2-3 Trees 362
Inserting Elements into a 2-3 Tree 362
Removing Elements from a 2-3 Tree 365
12.3 2-4 Trees 369
12.4 B-Trees 369
B*-trees 371
B+-trees 372
Analysis of B-trees 372
12.5 Implementation Strategies for B-Trees 373
Chapter 13 Graphs 377
13.1 Undirected Graphs 378
13.2 Directed Graphs 380
13.3 Networks 381
13.4 Common Graph Algorithms 382
Traversals 383
Testing for Connectivity 387
Minimum Spanning Trees 388
Determining the Shortest Path 391
13.5 Strategies for Implementing Graphs 392
Adjacency Lists 392
Adjacency Matrices 393
xxii CONTENTS
13.6 Implementing Undirected Graphs
with an Adjacency Matrix 395
The addEdge Method 399
The addVertex Method 400
The extendCapacity Method 401
Other Methods 401
Chapter 14 Hashing 407
14.1 Hashing 408
14.2 Hashing Functions 410
The Division Method 410
The Folding Method 411
The Mid-Square Method 411
The Radix Transformation Method 412
The Digit Analysis Method 412
The Length-Dependent Method 412
Hashing Functions in the Java Language 413
14.3 Resolving Collisions 413
Chaining 413
Open Addressing 416
14.4 Deleting Elements from a Hash Table 419
Deleting from a Chained Implementation 420
Deleting from an Open Addressing
Implementation 420
14.5 Hash Tables in the Java Collections API 421
The Hashtable Class 422
The HashSet Class 424
The HashMap Class 424
The IdentityHashMap Class 424
The WeakHashMap Class 425
LinkedHashSet and LinkedHashMap 428
Chapter 15 Sets and Maps 435
15.1 A Set Collection 436
15.2 Using a Set: Bingo 439
CONTENTS xxiii
15.3 Implementing a Set: With Arrays 443
The add Operation 445
The addAll Operation 447
The removeRandom Operation 448
The remove Operation 449
The union Operation 450
The contains Operation 451
The equals Operation 452
Other Operations 453
UML Description 453
15.4 Implementing a Set: With Links 455
The add Operation 456
The removeRandom Operation 457
The remove Operation 458
Other Operations 459
15.5 Maps and the Java Collections API 459
Appendix A UML 467
The Unified Modeling Language (UML) 468
UML Class Diagrams 468
UML Relationships 469
Appendix B Object-Oriented Design 475
B.1 Overview of Object-Orientation 476
B.2 Using Objects 476
Abstraction 477
Creating Objects 478
B.3 Class Libraries and Packages 480
The import Declaration 480
B.4 State and Behavior 481
B.5 Classes 482
Instance Data 485
B.6 Encapsulation 486
Visibility Modifiers 486
Local Data 488
xxiv CONTENTS
B.7 Constructors 488
B.8 Method Overloading 489
B.9 References Revisited 490
The null Reference 490
The this Reference 491
Aliases 493
Garbage Collection 494
Passing Objects as Parameters 495
B.10 The static Modifier 495
Static Variables 495
Static Methods 496
B.11 Wrapper Classes 497
B.12 Interfaces 498
The Comparable Interface 499
The Iterator Interface 500
B.13 Inheritance 500
Derived Classes 501
The protected Modifier 503
The super Reference 503
Overriding Methods 504
B.14 Class Hierarchies 504
The Object Class 505
Abstract Classes 506
Interface Hierarchies 508
B.15 Polymorphism 508
References and Class Hierarchies 509
Polymorphism via Inheritance 510
Polymorphism via Interfaces 512
B.16 Generic Types 514
B.17 Exceptions 515
Exception Messages 515
The try Statement 516
Exception Propagation 517
The Exception Class Hierarchy 517
Index 527
1
C H A P T E R
O B J E C T I V E S
■ Identify various aspects of
software quality
■ Motivate the need for data
structures based upon quality
issues
■ Introduce the basic concept of a
data structure
■ Introduce several elementary
data structures
Introduction
Our exploration of data structures begins with an
overview of the underlying issues surrounding the quality of
software systems. It is important for us to understand that it
is necessary for systems to work as specified, but simply
working is not sufficient. We must also develop quality sys-
tems. This chapter discusses a variety of issues related to
software quality and data structures, and it establishes some
terminology that is crucial to our exploration of data struc-
tures and software design.
1
1
2 CHAPTER 1 Introduction
1.1 Software Quality
Imagine a scenario where you are approaching a bridge that has recently been built over
a large river. As you approach, you see a sign informing you that the bridge was designed
and built by local construction workers and that engineers were not involved in the proj-
ect. Would you continue across the bridge? Would it make a difference if the sign in-
formed you that the bridge was designed by engineers and built by construction workers?
The word “engineer” in this context refers to an individual who has been educated
in the history, theory, method, and practice of the engineering discipline. This defini-
tion includes fields of study such as electrical engineering, mechanical engineering,
and chemical engineering. Software engineering is the study of the techniques and
theory that underlie the development of high-quality software.
When the term “software engineering” was first coined in the 1970s, it was an as-
piration—a goal set out by leaders in the industry who realized that much of the soft-
ware being created was of poor quality. They wanted developers to move away from
the simplistic idea of writing programs and toward the disciplined idea of engineering
software. To engineer software we must first realize that this term is more than just a
title and that it, in fact, represents a completely different attitude.
Many arguments have been started over the question of whether software engineer-
ing has reached the state of a true engineering discipline. We will leave that argument
for software engineering courses. For our purposes, it is sufficient to understand that as
software developers we share a common history, we are constrained by common the-
ory, and we must understand current methods and practices in order to work together.
Ultimately, we want to satisfy the client, the person or organization who pays
for the software to be developed, as well as the final users of the system, which
may include the client, depending on the situation.
The goals of software engineering are much the same as those for other engi-
neering disciplines:
■ Solve the right problem
■ Deliver a solution on time and within budget
■ Deliver a high-quality solution
■ Accomplish these things in an ethical manner (see www.acm.org/about/
code-of-ethics)
Sir Isaac Newton is credited with the quote “If I have seen further it is by stand-
ing on the shoulders of giants.” As modern software developers, we stand upon the
shoulders of the giants that founded and developed our field. To truly stand upon
their shoulders, we must understand, among other things, the fundamentals of
quality software systems and the organization, storage, and retrieval of data. These
are the building blocks upon which modern software development is built.
1.1 Software Quality 3
Quality Characteristic Description
The degree to which software adheres to its specific
requirements.
The frequency and criticality of software failure.
The degree to which erroneous situations are handled
gracefully.
The ease with which users can learn and execute tasks
within the software.
The ease with which changes can be made to the
software.
The ease with which software components can be
reused in the development of other software systems.
The ease with which software components can be
used in multiple computer environments.
The degree to which the software fulfills its purpose
without wasting resources.
Correctness
Reliability
Robustness
Usability
Maintainability
Reusability
Portability
Efficiency
FIGURE 1.1 Aspects of software quality
To maximize the quality of our software, we must first realize that quality
means different things to different people. And there are a variety of quality char-
acteristics to consider. Figure 1.1 lists several aspects of high-quality software.
Correctness
The concept of correctness goes back to our original goal to develop the appropriate
solution. At each step along the way of developing a program, we want to make sure
that we are addressing the problem as defined by the requirements specification and
that we are providing an accurate solution to that problem. Almost all other aspects
of quality are meaningless if the software doesn’t solve the right problem.
Reliability
If you have ever attempted to access your bank account electronically
and been unable to do so, or if you have ever lost all of your work be-
cause of a failure of the software or hardware you were using, you are
already familiar with the concept of reliability. A software failure can
be defined as any unacceptable behavior that occurs within permissi-
ble operating conditions. We can compute measures of reliability, such as the mean
time between failures or the number of operations or tasks between failures.
KEY CONCEPT
Reliable software seldom fails and,
when it does, it minimizes the effects
of that failure.
4 CHAPTER 1 Introduction
In some situations, reliability is an issue of life and death. In the early 1980s, a
piece of medical equipment called the Therac-25 was designed to deliver a dose
of radiation according to the settings made by a technician on a special key-
board. An error existed in the software that controlled the device and when the
technician made a very specific adjustment to the values on the keyboard, the in-
ternal settings of the device were changed drastically and a lethal dose of radia-
tion was issued. The error occurred so infrequently that several people died be-
fore the source of the problem was determined.
In other cases, reliability repercussions are financial. On a particular day in
November, 1998, the entire AT&T network infrastructure in the eastern United
States failed, causing major interruption in communications capabilities. The
problem was eventually traced back to a specific software error. That one failure
cost millions of dollars in lost revenue to the companies affected.
Robustness
Reliability is related to how robust a system is. A robust system handles
problems gracefully. For example, if a particular input field is designed to
handle numeric data, what happens when alphabetic information is entered?
The program could be allowed to terminate abnormally because of the result-
ing error. However, a more robust solution would be to design the system to
acknowledge and handle the situation transparently or with an appropriate
error message.
Developing a thoroughly robust system may or may not be worth the develop-
ment cost. In some cases, it may be perfectly acceptable for a program to abnor-
mally terminate if very unusual conditions occur. On the other hand, if adding
such protections is not excessively costly, it is simply considered to be good de-
velopment practice. Furthermore, well-defined system requirements should care-
fully spell out the situations in which robust error handling is required.
Usability
To be effective, a software system must be truly usable. If a system is too dif-
ficult to use, it doesn’t matter if it provides wonderful functionality. Within
the discipline of computer science there is a field of study called Human-
Computer Interaction (HCI) that focuses on the analysis and design of user
interfaces of software systems. The interaction between the user and system
must be well designed, including such things as help options, meaningful
messages, consistent layout, appropriate use of color, error prevention, and
error recovery.
1.1 Software Quality 5
Maintainability
Software developers must maintain their software. That is, they
must make changes to software in order to fix errors, to enhance
the functionality of the system, or simply to keep up with evolving
requirements. A useful software system may need to be maintained
for many years after its original development. The software engi-
neers who perform maintenance tasks are often not the same ones as
those who originally developed the software. Thus, it is important that a software
system be well structured, well written, and well documented in order to maxi-
mize its maintainability.
Large software systems are rarely written by a single individual or even a small
group of developers. Instead, large teams, often working from widely distributed
locations, work together to develop systems. For this reason, communication
among developers is critical. Therefore, creating maintainable software is benefi-
cial for the long term as well as for the initial development effort.
Reusability
Suppose that you are a contractor involved in the construction of an office building.
It is possible that you might design and build each door in the building from
scratch. This would require a great deal of engineering and construction effort, not
to mention money. Another option is to use pre-engineered, prefabricated doors for
the doorways in the building. This approach represents a great savings of time and
money because you can rely on a proven design that has been used many times be-
fore. You can be confident that it has been thoroughly tested and that you know its
capabilities. However, this does not exclude the possibility that a few doors in the
building will be custom engineered and custom built to fit a specific need.
When developing a software system, it often makes sense to use pre-existing
software components if they fit the needs of the developer and the client. Why
reinvent the wheel? Pre-existing components can range in scope from the entire
system, to entire subsystems, to individual classes and methods. They may come
from part of another system developed earlier or from libraries of components that
are created to support the development of future systems. Some pre-existing com-
ponents are referred to as Commercial Off-The-Shelf (COTS) products. Pre-exist-
ing components are often reliable because they have been tested in other systems.
Using pre-existing components can reduce the development effort. However,
reuse comes at a price. The developer must take the time to investigate potential
components to find the right one. Often the component must be modified or ex-
tended to fit the criteria of the new system. Thus, it is helpful if the component is
truly reusable. That is, software should be written and documented so that it can
KEY CONCEPT
Software systems must be carefully
designed, written, and documented
to support the work of developers,
maintainers, and users.
6 CHAPTER 1 Introduction
be easily incorporated into new systems and easily modified or extended to ac-
commodate new requirements.
Portability
Software that is easily portable, can be moved from one computing environment
to another with little or no effort. Software developed using a particular operat-
ing system and underlying central processing unit (CPU) may not run well or at
all in another environment. One obvious problem is a program that has been
compiled into a particular CPU’s machine language. Because each type of CPU
has its own machine language, porting it to another machine would require an-
other, translated version. Differences in the various translations may cause the
“same” program on two types of machines to behave differently.
Using the Java programming language addresses this issue because Java source-
code is compiled into bytecode, which is a low-level language that is not the ma-
chine language for any particular CPU. Bytecode runs on a Java Virtual Machine
(JVM), which is software that interprets the bytecode and executes it. Therefore,
at least theoretically, any system that has a JVM can execute any Java program.
Efficiency
The last software quality characteristic listed in Figure 1.1 is efficiency. Software
systems should make efficient use of the resources allocated to them. Two key re-
sources are CPU time and memory. User demands on computers
and their software have risen steadily ever since computers were
first created. Software must always make the best use of its re-
sources in order to meet those demands. The efficiency of individ-
ual algorithms is an important part of this issue and is discussed in
more detail in the next chapter and throughout the book.
Quality Issues
To a certain extent, quality is in the eye of the beholder. That is, some quality
characteristics are more important to certain people than to others. We must con-
sider the needs of the various stakeholders, the people affected one
way or another by the project. For example, the end user certainly
wants to maximize reliability, usability, and efficiency, but doesn’t
necessarily care about the software’s maintainability or reusability.
The client wants to make sure the user is satisfied, but is also wor-
ried about the overall cost. The developers and maintainers want the
internal system quality to be high.
KEY CONCEPT
Software must make efficient use of
resources such as CPU time and
memory.
KEY CONCEPT
Quality characteristics must be
prioritized, and then maximized to
the extent possible.
1.2 Data Structures 7
Note also that some quality characteristics are in competition with each other. For
example, to make a program more efficient, we may choose to use a complex algo-
rithm that is difficult to understand and therefore hard to maintain. These types of
trade-offs require us to carefully prioritize the issues related to a particular project
and, within those boundaries, maximize all quality characteristics as much as possi-
ble. If we decide that we must use the more complex algorithm for efficiency, we can
also document the code especially well to assist with future maintenance tasks.
Although all of these quality characteristics are important, for our exploration
of data structures in this book, we will focus upon reliability, robustness, reusabil-
ity and efficiency. In the creation of data structures, we are not creating applica-
tions or end-user systems but rather reusable components that may be used in a
variety of systems. Thus, usability is not an issue since there will not be a user in-
terface component of our data structures. By implementing in Java and adhering
to Javadoc standards, we also address the issues of portability and maintainability.
1.2 Data Structures
Why spend so much time talking about software engineering and software quality
in a text that focuses on data structures and their algorithms? Well, as you begin
to develop more complex programs, it’s important to develop a more mature out-
look on the process. As we discussed at the beginning of this chapter, the goal
should be to engineer software, not just write code. The data structures we exam-
ine in this book lay the foundation for complex software that must be carefully
designed. Let’s consider an example that will illustrate the need for and the vari-
ous approaches to data structures.
A Physical Example
Imagine that you must design the process for how to handle shipping containers
being unloaded from cargo ships at a dock. In a perfect scenario, the trains and
trucks that will haul these containers to their destinations will be waiting as the
ship is unloaded and thus there would not be a need to store the containers at all.
However, such timing is unlikely, and would not necessarily provide the most effi-
cient result for the trucks and the trains since they would have to sit and wait
while each ship was unloaded. Instead, as each shipping container is unloaded
from a ship, it is moved to a storage location where it will be held until it is
loaded on either a truck or a train. Our goal should be to make both the unload-
ing of containers and the retrieval of containers for transportation as efficient as
possible. This will mean minimizing the amount of searching required in either
process and minimizing the number of times a container is moved.
8 CHAPTER 1 Introduction
Before we go any further, let’s examine the initial assumptions underlying this
problem. First, our shipping containers are generic. By that we mean that they are
all the same shape, same size, and can hold the same volume and types of materials.
Second, each shipping container has a unique identification number. This number
is the key that determines the final destination of each container and whether it is
to be shipped by truck or train. Third, the dock workers handling the containers
do not need to know, nor can they know, what is inside of each container.
Given these assumptions as a starting point, how might we design our storage
process for these containers? One possibility might be to simply lay out a very
large array indexed by the identification number of the container. Keep in mind,
however, the identification number is unique, not just for a single ship but for all
ships and all shipping containers. That means that we would need to layout an ar-
ray of storage at each dock large enough to handle all of the shipping containers
in the world. This would also mean that at any given point in time, the vast ma-
jority of the units in these physical arrays would be empty. This would appear to
be a terrible waste of space and very inefficient. We will explore issues surround-
ing the efficiency of algorithms in the next chapter.
We could try this same solution but allow the array to collapse and expand like
an ArrayList as containers are removed or added. However, given the physical
nature of this array, such a solution may involve having to move containers multi-
ple times as other containers with lower ID numbers are added or removed.
Again, such a solution would be very inefficient.
What if we could estimate the maximum number of shipping containers that
we would be storing on our dock at any given point in time? This would create
the possibility of creating an array of that maximum size and then simply placing
each container into the next available position in the array as it is unloaded from
the ship. This would be relatively efficient for unloading purposes since the dock
workers would simply keep track of which locations in the array were empty and
place each new container in an empty location. However, using this approach,
what would happen when a truck driver arrived looking for a particular con-
tainer? Since the array is not ordered by container ID, the driver would have to
search for the container in the array. In the worst case scenario, the container they
are seeking would be the last one in the array causing them to search the entire ar-
ray. Of course, the average case would be that each driver would have to search
half of the array. Again, this seems less efficient than it could be.
Before we try a new design, let’s reconsider what we know about each container.
Of course, we have the container ID. But from that, we also have the destination of
each container. What if instead of an abitrary ordering of containers in a one-
dimensional array, we create a two-dimensional array where the first dimension is
the destination? Thus we can implement our previous solution as the second dimen-
sion within each destination. Unloading a container is still quite simple. The dock
1.2 Data Structures 9
workers would simply take the container to the array for its destination and place it
in the first available empty slot. Then our truck drivers would not have to search
the entire dock for their shipping container, only that portion, the array within the
array, that is bound for their destination. This solution, which is beginning to be-
have like a data structure called a hash table (discussed in Chapter 13), is an im-
provement but still requires searching at least a portion of the storage.
The first part of this solution, organizing the first dimension by destination,
seems like a good idea. However, using a simple unordered array for the second
dimension still does not accomplish our goal. There is one additional piece of in-
formation that we have for each container that we have yet to examine—the
order that it has been unloaded from the ship. Let’s consider an example for a
moment of the components of an oil rig being shipped in multiple containers.
Does the order of those containers matter? Yes. The crew constructing the oil rig
must receive and install the foundation and base components before being able to
construct the top of the rig. Now the order the containers are removed from the
ship and the order they are placed in storage is important. To this point, we have
been considering only the problem of unloading, storing, and shipping storage
containers. Now we begin to see that this problem exists within a larger context
including how the ship was loaded at its point of origin. Three possibilities exist
for how the ship was loaded: containers that are order dependent were loaded in
the order they are needed, containers that are order dependent were loaded in the
reverse order they are needed, or containers that are order dependent were loaded
without regard to order but with order included as part of the information associ-
ated with the container ID. Let’s consider each of these cases separately.
Keep in mind that the process of unloading the ship will reverse the order of the
loading process onto the ship. This behavior is very much like that of a stack, data
structure, which we will discuss further in Chapters 3 and 4. If the ship was loaded
in the order the components are needed, then the unloading process will reverse the
order. Thus our storage and retrieval process must reverse the order again in order
to get the containers back into the correct order. This would be accomplished by
taking the containers to the array for their destination and storing them in the order
they were unloaded. Then the trucker retrieving these containers would simply start
with the last one stored. Finally, with this solution we have a storage and retrieval
process that involves no searching at all and no extra handling of containers.
What if the containers were loaded onto the ship in the reverse or-
der they are needed? In that case, unloading the ship will bring the
containers off in the order they will be needed and our storage and
retrieval process must preserve that order. This would be accom-
plished by taking the containers to the array for their destination,
storing them in the order they were unloaded, and then having the truckers start
with the first container stored rather than the last. Again, this solution does not
KEY CONCEPT
A stack can be used to reverse the
order of a set of data.
10 CHAPTER 1 Introduction
involve any searching or extra handling of containers. This behavior is that of a
queue data structure, which will be discussed in detail in Chapter 5.
Both of our previous solutions, while very efficient, have been de-
pendent upon the order that the containers were placed aboard ship.
What do we do if the containers were not placed aboard in any par-
ticular order? In that case, we will need to order the destination array
by the priority order of the containers. Rather than trying to exhaust
this example, let’s just say that there are several data structures that might accom-
plish this purpose including ordered lists (Chapter 6), priority queues and heaps
(Chapter 11), and hash tables (Chapter 13). We also have the additional issue of
how best to organize the file that relates container IDs to the other information
about each container. Solutions to this problem might include binary search trees
(Chapter 10) and multi-way search trees (Chapter 12).
Containers as Objects
Our shipping container example illustrates another issue surrounding data struc-
tures beyond our discussion of how to store the containers. It also illustrates the
issue of what the containers store. Early in our discussion, we made the assump-
tion that all shipping containers have the same shape and same size, and can hold
the same volume and type of material. While the first two assumptions must re-
main true in order for containers to be stored and shipped interchangeably, the
latter assumptions may not be true.
For example, consider the shipment of materials that must remain refrigerated.
It may be useful to develop refrigerated shipping containers for this purpose.
Similarly some products require very strict humidity control and might require a
container with additional environmental controls. Others might be designed for
hazardous material and may be lined and/or double walled for protection. Once
we develop multiple types of containers, then our containers are no longer
generic. We can then think of shipping containers as a hierarchy much like a class
hierarchy in object-oriented programming. Thus assigning material to a shipping
container becomes analogous to assigning an object to a reference. With both
shipping containers and objects, not all assignments are valid. We will discuss is-
sues of type compatibility, inheritance, polymorphism, and creating generic data
structures in Chapter 3.
KEY CONCEPT
A queue preserves the order of its
data.
Summary of Key Concepts 11
Summary of Key Concepts
■ Reliable software seldom fails and, when it does, it minimizes the effects of
that failure.
■ Software systems must be carefully designed, written, and documented to
support the work of developers, maintainers, and users.
■ Software must make efficient use of resources such as CPU time and
memory.
■ Quality characteristics must be prioritized, and then maximized to the extent
possible.
■ A stack can be used to reverse the order of a set of data.
■ A queue preserves the order of its data.
Self-Review Questions
SR 1.1 What is the difference between software engineering and pro-
gramming?
SR 1.2 Name several software quality characteristics.
SR 1.3 What is the relationship between reliability and robustness?
SR 1.4 Describe the benefits of developing software that is maintainable.
SR 1.5 How does the Java programming language address the quality
characteristic of portability?
SR 1.6 What is the principle difference in behavior between a stack and a
queue?
SR 1.7 List two common data structures that might be used to order a
set of data.
Exercises
EX 1.1 Compare and contrast software engineering with other engineer-
ing disciplines.
EX 1.2 Give a specific example that illustrates each of the software qual-
ity characteristics listed in Figure 1.1.
EX 1.3 Provide an example, and describe the implications, of a trade-off
that might be necessary between quality characteristics in the de-
velopment of a software system.
12 CHAPTER 1 Introduction
Answers to Self-Review Questions
SRA 1.1 Software engineering is concerned with the larger goals of system
design and development, not just the writing of code. Programmers
mature into software engineers as they begin to understand the
issues related to the development of high-quality software and
adopt the appropriate practices.
SRA 1.2 Software quality characteristics include: correctness, reliability,
robustness, usability, maintainability, reusability, portability, and
efficiency.
SRA 1.3 Reliability is concerned with how often and under what circum-
stances a software system fails, and robustness is concerned with
what happens when a software system fails.
SRA 1.4 Software that is well structured, well designed, and well docu-
mented is much easier to maintain. These same characteristics
also provide benefit for distributed development.
SRA 1.5 The Java programming language addresses this issue by compiling
into bytecode, which is a low-level language that is not the ma-
chine language for any particular CPU. Bytecode runs on a Java
Virtual Machine (JVM), which is software that interprets the
bytecode and executes it. Therefore, at least theoretically, any sys-
tem that has a JVM can execute any Java program.
SRA 1.6 A stack reverses order whereas a queue preserves order.
SRA 1.7 Common data structures that can be used to order a set of data
include ordered lists, heaps, and hash tables.
13
C H A P T E R
O B J E C T I V E S
■ Discuss the goals of software
development with respect to
efficiency
■ Introduce the concept of
algorithm analysis
■ Explore the concept of
asymptotic complexity
■ Compare various growth
functions
Analysis of
Algorithms
It is important that we understand the concepts surround-
ing the efficiency of algorithms before we begin building
data structures. A data structure built correctly and with an
eye toward efficient use of both the CPU and memory is one
that can be reused effectively in many different applications.
However, a data structure that is not built efficiently is simi-
lar to using a damaged original as the master from which to
make copies.
2
2
14 CHAPTER 2 Analysis of Algorithms
2.1 Algorithm Efficiency
One of the quality characteristics discussed in section 1.1 is the efficient use of re-
sources. One of the most important resources is CPU time. The efficiency of an al-
gorithm we use to accomplish a particular task is a major factor that determines
how fast a program executes. Although the techniques that we will discuss here
may also be used to analyze an algorithm relative to the amount of memory it
uses, we will focus our discussion on the efficient use of processing time.
The analysis of algorithms is a fundamental computer science topic
and involves a variety of techniques and concepts. It is a primary
theme that we return to throughout this book. This chapter introduces
the issues related to algorithm analysis and lays the groundwork for
using analysis techniques.
Let’s start with an everyday example: washing dishes by hand. If we assume
that washing a dish takes 30 seconds and drying a dish takes an additional 30 sec-
onds, then we can see quite easily that it would take n minutes to wash and dry n
dishes. This computation could be expressed as follows:
Time (n dishes) = n * (30 seconds wash time + 30 seconds dry time)
= 60n seconds
or, written more formally:
f(x) = 30x + 30x
f(x) = 60x
On the other hand, suppose we were careless while washing the dishes and
splashed too much water around. Suppose each time we washed a dish, we had to
dry not only that dish but also all of the dishes we had washed before that one. It
would still take 30 seconds to wash each dish, but now it would take 30 seconds
to dry the last dish (once), 2 * 30 or 60 seconds to dry the second-to-last dish
(twice), 3 * 30 or 90 seconds to dry the third-to-last dish (three times), and so on.
This computation could be expressed as follows:
Using the formula for an arithmetic series then the function
becomes
Time (n dishes) = 30n + 30n(n + 1)/2
= 15n2 + 45n seconds
If there were 30 dishes to wash, the first approach would take 30 minutes,
whereas the second (careless) approach would take 247.5 minutes. The more dishes
g
n
1 i = n(n + 1)/2
Time (n dishes) = n * (30 seconds wash time) + a
n
i=1
(i * 30)
KEY CONCEPT
Algorithm analysis is a fundamental
computer science topic.
2.2 Growth Functions and Big-OH Notation 15
we wash the worse that discrepancy becomes. For example, if there were 300 dishes
to wash, the first approach would take 300 minutes or 5 hours, whereas the second
approach would take 908,315 minutes or roughly 15,000 hours!
2.2 Growth Functions and Big-OH Notation
For every algorithm we want to analyze, we need to define the size of the problem.
For our dishwashing example, the size of the problem is the number of dishes to be
washed and dried. We also must determine the value that represents efficient use of
time or space. For time considerations, we often pick an appropriate processing
step that we’d like to minimize, such as our goal to minimize the number of times
a dish has to be washed and dried. The overall amount of time spent on the task is
directly related to how many times we have to perform that task. The algorithm’s
efficiency can be defined in terms of the problem size and the processing step.
Consider an algorithm that sorts a list of numbers into increasing
order. One natural way to express the size of the problem would be
the number of values to be sorted. The processing step we are trying
to optimize could be expressed as the number of comparisons we
have to make for the algorithm to put the values in order. The more
comparisons we make, the more CPU time is used.
A growth function shows the relationship between the size of the problem (n)
and the value we hope to optimize. This function represents the time complexity
or space complexity of the algorithm.
The growth function for our second dishwashing algorithm is
t(n) = 15n2 + 45n
However, it is not typically necessary to know the exact growth function for an
algorithm. Instead, we are mainly interested in the asymptotic complexity of an
algorithm. That is, we want to focus on the general nature of the function as n in-
creases. This characteristic is based on the dominant term of the expression—the
term that increases most quickly as n increases. As n gets very large, the value of
the dishwashing growth function is dominated by the n2 term because the n2 term
grows much faster than the n term. The constants, in this case 15 and 45, and the
secondary term, in this case 45n, quickly become irrelevant as n increases. That is
to say, the value of n2 dominates the growth in the value of the expression.
The table in Figure 2.1 shows how the two terms and the value of the expres-
sion grow. As you can see from the table, as n gets larger, the 15n2 term domi-
nates the value of the expression. It is important to note that the 45n term is
larger for very small values of n. Saying that a term is the dominant term as n gets
large does not mean that it is larger than the other terms for all values of n.
KEY CONCEPT
A growth function shows time or
space utilization relative to the
problem size.
16 CHAPTER 2 Analysis of Algorithms
The asymptotic complexity is called the order of the algorithm. Thus, our sec-
ond dishwashing algorithm is said to have order n2 time complexity, written
O(n2). Our first, more efficient dishwashing example, with growth function t(n) =
60(n) would have order n, written O(n). Thus the reason for the difference be-
tween our O(n) original algorithm and our O(n2) sloppy algorithm is the fact
each dish will have to be dried multiple times.
This notation is referred to as O() or Big-Oh notation. A growth function that
executes in constant time regardless of the size of the problem is said to have
O(1). In general, we are only concerned with executable statements in a program
or algorithm in determining its growth function and efficiency. Keep in mind,
however, that some declarations may include initializations and some of these
may be complex enough to factor into the efficiency of an algorithm.
As an example, assignment statements and if statements that are
only executed once regardless of the size of the problem are O(1).
Therefore, it does not matter how many of those you string together; it
is still O(1). Loops and method calls may result in higher order growth
functions because they may result in a statement or series of statements
being executed more than once based on the size of the problem. We
will discuss these separately in later sections of this chapter. Figure 2.2 shows several
growth functions and their asymptotic complexity.
More formally, saying that the growth function t(n) = 15n2 + 45n is
O(n2) means that there exists a constant m and some value of n (n0),
such that t(n) … m*n2 for all n 7 n0. Another way of stating this is that
the order of an algorithm provides an upper bound to its growth func-
tion. It is also important to note that there are other related notations
such as omega (Ω) which refers to a function that provides a lower
Number of dishes (n)
1
2
5
10
100
1,000
10,000
100,000
1,000,000
10,000,000
15
60
375
1,500
150,000
15,000,000
1,500,000,000
150,000,000,000
15,000,000,000,000
1,500,000,000,000,000
15n2
45
90
225
450
4,500
45,000
450,000
4,500,000
45,000,000
450,000,000
45n
60
150
600
1,950
154,500
15,045,000
1,500,450,000
150,004,500,000
15,000,045,000,000
1,500,000,450,000,000
15n2 ⴙ 45n
FIGURE 2.1 Comparison of terms in growth function
KEY CONCEPT
The order of an algorithm provides
an upper bound to the algorithm’s
growth function.
KEY CONCEPT
The order of an algorithm is found by
eliminating constants and all but the
dominant term in the algorithm’s
growth function.
2.3 Comparing Growth Functions 17
bound and theta (Θ) which refers to a function that provides both an upper and
lower bound. We will focus our discussion on order.
Because the order of the function is the key factor, the other terms and constants
are often not even mentioned. All algorithms within a given order are considered to
be generally equivalent in terms of efficiency. For example, while two algorithms to
accomplish the same task may have different growth functions, if they are both
O(n2) then they are considered to be roughly equivalent with respect to efficiency.
2.3 Comparing Growth Functions
One might assume that, with the advances in the speed of processors and the avail-
ability of large amounts of inexpensive memory, algorithm analysis would no
longer be necessary. However, nothing could be farther from the truth. Processor
speed and memory cannot make up for the differences in efficiency of algorithms.
Keep in mind that in our previous discussion we have been eliminating constants as
irrelevant when discussing the order of an algorithm. Increasing processor speed
simply adds a constant to the growth function. When possible, finding a more effi-
cient algorithm is a better solution than finding a faster processor.
Another way of looking at the effect of algorithm complexity was proposed by
Aho, Hopcroft, and Ullman (1974). If a system can currently handle a problem of
size n in a given time period, what happens to the allowable size of the problem if we
increase the speed of the processor tenfold? As shown in Figure 2.3, the linear
case is relatively simple. Algorithm A, with a linear time complexity of n, is indeed
improved by a factor of 10, meaning that this algorithm can process 10 times the
data in the same amount of time given a tenfold speed up of the processor. However,
algorithm B, with a time complexity of n2, is only improved by a factor of 3.16. Why
do we not get the full tenfold increase in problem size? Because the complexity of
algorithm B is n2 our effective speedup is only the square root of 10 or 3.16.
Growth Function
t(n) = 17
t(n) = 3log n
t(n) = 20n – 4
t(n) = 12n log n + 100n
t(n) = 3n2 + 5n – 2
t(n) = 8n3 + 3n2
t(n) = 2n + 18n2 + 3n
O(1)
O(log n)
O(n)
O(n log n)
O(n2)
O(n3)
O(2n)
Order
constant
logarithmic
linear
n log n
quadratic
cubic
exponential
Label
FIGURE 2.2 Some growth functions and their asymptotic complexity
18 CHAPTER 2 Analysis of Algorithms
Similarly, algorithm C, with complexity n3, is only improved by a
factor of 2.15 or the cube root of 10. For algorithms with
exponential complexity like algorithm D, in which the size variable is
in the exponent of the complexity term, the situation is far worse. In
this case the speed up is log2n or in this case, 3.3. Note this is not a
factor of 3, but the original problem size plus 3. In the grand scheme
of things, if an algorithm is inefficient, speeding up the processor will not help.
Figure 2.4 illustrates various growth functions graphically for relatively small
values of n. Note that when n is small, there is little difference between the algo-
Algorithm
A
B
C
D
Time Complexity
n
n2
n3
2n
Max Problem Size
Before Speedup
s1
s2
s3
s4
Max Problem Size
After Speedup
10s1
3.16s2
2.15s3
s4 + 3.3
FIGURE 2.3 Increase in problem size with a tenfold increase in processor speed
500
200
100
0
Time
1 5 10 15 25
20
300
400
Input Size (N)
log n
n
n log n
n2
n3
2n
FIGURE 2.4 Comparison of typical growth functions for small values of n
KEY CONCEPT
If the algorithm is inefficient, a faster
processor will not help in the long
run.
2.4 Determining Time Complexity 19
rithms. That is, if you can guarantee a very small problem size (5 or less), it doesn’t
really matter which algorithm is used. However, notice that in Figure 2.5, as n gets
very large, the differences between the growth functions become obvious.
2.4 Determining Time Complexity
Analyzing Loop Execution
To determine the order of an algorithm, we have to determine how
often a particular statement or set of statements gets executed.
Therefore, we often have to determine how many times the body of a
loop is executed. To analyze loop execution, first determine the order
of the body of the loop, and then multiply that by the number of
times the loop will execute relative to n. Keep in mind that n repre-
sents the problem size.
200,000
100,000
50,000
0
Time
150,000
100
1 200 300 500
400
log n
n
n log n
n2
n3
2n
Input Size (N)
FIGURE 2.5 Comparison of typical growth functions for large values of n
KEY CONCEPT
Analyzing algorithm complexity of-
ten requires analyzing the execution
of loops.
20 CHAPTER 2 Analysis of Algorithms
Assuming that the body of a loop is O(1), then a loop such as this:
for (int count = 0; count < n; count++)
{
/* some sequence of O(1) steps */
}
would have O(n) time complexity. This is due to the fact that the body of the loop
has O(1) complexity but is executed n times by the loop structure. In general, if a
loop structure steps through n items in a linear fashion and the body of the loop is
O(1), then the loop is O(n). Even in a case where the loop is designed to skip
some number of elements, as long as the progression of elements to skip is linear,
the loop is still O(n). For example, if the preceding loop skipped every other num-
ber (e.g. count += 2), the growth function of the loop would be n/2, but since con-
stants don’t affect the asymptotic complexity, the order is still O(n).
Let’s look at another example. If the progression of the loop is logarithmic
such as the following:
count = 1
while (count < n)
{
count *= 2;
/* some sequence of O(1) steps */
}
then the loop is said to be O(log n). Note that when we use a loga-
rithm in an algorithm complexity, we almost always mean log base
2. This can be explicitly written as O(log2n). Since each time through
the loop the value of count is multiplied by 2, the number of times
the loop is executed is log2n.
Nested Loops
A slightly more interesting scenario arises when loops are nested. In this case, we
must multiply the complexity of the outer loop by the complexity of the inner
loop to find the resulting complexity. For example, the following nested loops:
for (int count = 0; count < n; count++)
{
for (int count2 = 0; count2 < n; count2++)
{
/* some sequence of O(1) steps */
}
}
KEY CONCEPT
The time complexity of a loop is
found by multiplying the complexity
of the body of the loop by how many
times the loop will execute.
2.4 Determining Time Complexity 21
would have complexity O(n2). The body of the inner loop is O(1)
and the inner loop will execute n times. This means the inner loop is
O(n). Multiplying this result by the number of times the outer loop
will execute (n) results in O(n2).
What is the complexity of the following nested loop?
for (int count = 0; count < n; count++)
{
for (int count2 = count; count2 < n; count2++)
{
/* some sequence of O(1) steps */
}
}
In this case, the inner loop index is initialized to the current value of the index
for the outer loop. The outer loop executes n times. The inner loop executes n
times the first time, n–1 times the second time, etc. However, remember that we
are only interested in the dominant term, not in constants or any lesser terms. If
the progression is linear, regardless of whether some elements are skipped, the or-
der is still O(n). Thus the resulting complexity for this code is O(n2).
Method Calls
Let’s suppose that we have the following segment of code:
for (int count = 0; count < n; count++)
{
printsum (count);
}
We know from our previous discussion that we find the order of the loop by
multiplying the order of the body of the loop by the number of times the loop will
execute. In this case, however, the body of the loop is a method call. Therefore,
we must first determine the order of the method before we can determine the or-
der of the code segment. Let’s suppose that the purpose of the method is to print
the sum of the integers from 1 to n each time it is called. We might be tempted to
create a brute force method such as the following:
public void printsum(int count)
{
int sum = 0;
for (int I = 1; I < count; I++)
sum += I;
System.out.println (sum);
}
KEY CONCEPT
The analysis of nested loops must
take into account both the inner and
outer loops.
22 CHAPTER 2 Analysis of Algorithms
What is the time complexity of this printsum method? Keep in mind that
only executable statements contribute to the time complexity so in this case, all
of the executable statements are O(1) except for the loop. The loop on the other
hand is O(n) and thus the method itself is O(n). Now to compute the time com-
plexity of the original loop that called the method, we simply multiply the
complexity of the method, which is the body of the loop, by the number of
times the loop will execute. Our result, then, is O(n2) using this implementa-
tion of the printsum method.
However, if you recall, we know from our earlier discussion that we do not have
to use a loop to calculate the sum of the numbers from 1 to n. In fact, we know that
the Now let’s rewrite our printsum method and see what hap-
pens to our time complexity:
public void printsum(int count)
{
sum = count*(count+1)/2;
System.out.println (sum);
}
Now the time complexity of the printsum method is made up of an assign-
ment statement which is O(1) and a print statement which is also O(1). The result
of this change is that the time complexity of the printsum method is now O(1)
meaning that the loop that calls this method now goes from being O(n2) to O(n).
We know from our our earlier discussion and from Figure 2.5 that this is a very
significant improvement. Once again we see that there is a difference between
delivering correct results and doing so efficiently.
What if the body of a method is made up of multiple method calls and loops?
Consider the following code using our printsum method above:
g
n
1i = n(n + 1)/2.
/* this method call is O(1) */
/* this loop is O(n) */
/* this loop is O(n2) */
public void sample(int n)
{
printsum(n);
for (int count = 0; count < n; count++)
printsum (count);
for (int count = 0; count < n; count++)
for (int count2 = 0; count2 < n; count2++)
System.out.println (count, count2);
}
The initial call to the printsum method with the parameter temp is O(1) since
the method is O(1). The for loop containing the call to the printsum method
with the parameter count is O(n) since the method is O(1) and the loop executes
2.4 Determining Time Complexity 23
n times. The nested loops are O(n2) since the inner loop will execute n times each
time the outer loop executes and the outer loop will also execute n times. The en-
tire method is then O(n2) since only the dominant term matters.
More formally, the growth function for the method sample is given by:
f(x) = 1 + n + n2
Then given that we eliminate constants and all but the dominant term, the time
complexity is O(n2).
There is one additional issue to deal with when analyzing the time complexity
of method calls and that is recursion, the situation when a method calls itself. We
will save that discussion for Chapter 7.
Summary of Key Concepts
■ Software must make efficient use of resources such as CPU time and memory.
■ Algorithm analysis is a fundamental computer science topic.
■ A growth function shows time or space utilization relative to the problem size.
■ The order of an algorithm is found by eliminating constants and all but the
dominant term in the algorithm’s growth function.
■ The order of an algorithm provides an upper bound to the algorithm’s
growth function.
■ If the algorithm is inefficient, a faster processor will not help in the long run.
■ Analyzing algorithm complexity often requires analyzing the execution of
loops.
■ The time complexity of a loop is found by multiplying the complexity of the
body of the loop by how many times the loop will execute.
■ The analysis of nested loops must take into account both the inner and outer
loops.
Self-Review Questions
SR 2.1 What is the difference between the growth function of an algo-
rithm and the order of that algorithm?
SR 2.2 Why does speeding up the CPU not necessarily speed up the
process by the same amount?
SR 2.3 How do we use the growth function of an algorithm to determine
its order?
SR 2.4 How do we determine the time complexity of a loop?
SR 2.5 How do we determine the time complexity of a method call?
Exercises
EX 2.1 What is the order of the following growth functions?
a. 10n2 + 100n + 1000
b. 10n3 – 7
c. 2n + 100n3
d. n2 log n
24 CHAPTER 2 Analysis of Algorithms
EX 2.2 Arrange the growth functions of the previous exercise in ascend-
ing order of efficiency for n=10 and again for n=1,000,000.
EX 2.3 Write the code necessary to find the largest element in an unsorted
array of integers. What is the time complexity of this algorithm?
EX 2.4 Determine the growth function and order of the following code
fragment:
for (int count=0; count < n; count++)
{
for (int count2=0; count2 < n; count2=count2+2)
{
System.out.println(count, count2);
}
}
EX 2.5 Determine the growth function and order of the following code
fragment:
for (int count=0; count < n; count++)
{
for (int count2=0; count2 < n; count2=count2*2)
{
System.out.println(count, count2);
}
}
EX 2.6 The table in Figure 2.1 shows how the terms of the growth func-
tion for our dishwashing example relate to one another as n
grows. Write a program that will create such a table for any given
growth function.
Answers to Self-Review Questions
SRA 2.1 The growth function of an algorithm represents the exact rela-
tionship between the problem size and the time complexity of the
solution. The order of the algorithm is the asymptotic time com-
plexity. As the size of the problem grows, the complexity of the
algorithm approaches the asymptotic complexity.
SRA 2.2 Linear speedup only occurs if the algorithm has constant order,
O(1), or linear order, O(n). As the complexity of the algorithm
grows, faster processors have significantly less impact.
SRA 2.3 The order of an algorithm is found by eliminating constants and
all but the dominant term from the algorithm’s growth function.
Answers to Self Review Questions 25
Other documents randomly have
different content
The data regarding your prospective customer is obtainable in
many ways. Much of it you may obtain from your house if they have
had previous dealings with him. Other salesmen will also add to the
data, but one must be on the lookout here and not allow himself to
be prejudiced against the customer, or frightened by adverse reports
regarding his manner and characteristics coming from other
salesmen. Pierce says: "It would seem that the good characteristics
of the prospect are desirable to learn. But it is a conviction that by
denying to one's self the unfavorable things said about your
prospect, you will not accentuate the very qualities you hope to
obviate. One attempt at a sale is recalled where the prospect was
said to be 'the meanest man on earth.' Almost terrified by the
description, the salesman went at the prospect the wrong way;
displeased him; lost the sale."
Hotel clerks—or better still, hotel proprietors—are often very well
informed regarding merchants in their town, and often valuable
information may be obtained in this way, although the judgment and
experience of the hotel people must be appraised before basing
one's own opinion regarding the customer. Other customers may
also be diplomatically pressed into service in obtaining information
regarding their competitors, although allowance must always be
made for the personal bias in such cases. It is a good idea for the
salesman to make a record of these advance reports, so as to have
them on file where he may refer to them when needed. Some
salesmen have a card index devoted to this purpose, which they
have found very useful.
Another, and a very important point about the Pre-Approach is
that of developing the proper Mental Attitude in yourself. You must
get yourself right first, before you can get anything else right. Pierce
says regarding this: "Someone has said that the greatest bane to
selling goods is fear. As a matter of fact, the only thing you are
afraid of is that you won't make the sale,—get the check. But, if you
waive this point, and say, 'Now, I don't care whether I get this sale
or not. I do know this: I am honest, my goods are honest, and if this
man does not want them there are plenty of men who do,' you will
find the fear melting like the mist before sunshine. Fear cannot live
in the presence of your smile, your confidence, your knowledge of
the business and your industry."
In this connection, re-read what we have said to you regarding
the "I" and "Self-Respect" in the chapter entitled "The Mind of the
Salesman." This chapter was written to cover just such cases as the
one in question. If you can realize the "I" within you, your fear will
disappear quickly. Remember, "there's nothing to fear but Fear."
Many successful salesmen state that they overcame their early
fear and timidity by filling themselves with auto-suggestions that
they were calling on the customer for the purpose of doing him a
good turn—that it was a good thing for the customer that the
salesman was calling on him, although he did not know it—and that
he, the salesman must let nothing stand in the way of doing that
good turn to the customer, etc. As ridiculous as this may appear to
some, it will be found to work well in many cases. And it is based
upon truth, too, for if the goods are right, and the prices are
likewise, the salesman is doing the customer a good turn.
And right here, let us impress upon you the necessity of working
yourself up to the point of believing thoroughly in your own
proposition. You must get yourself into the state of mind in which, if
you were in the customer's place, you would surely want to take
advantage of it. You must convert yourself before you can expect to
convert the customer. We know an ad. man who tells us that he
never feels satisfied with an ad. that he is writing until he can make
himself believe that he wants to buy the article himself. And he is
right. And the salesman will do well to take a leaf from his book.
Enthusiasm and belief are contagious. If you believe thoroughly in a
thing, you run a much better chance of making others believe in it
also, than if you feel otherwise. You must learn to sell to yourself
first, then you may sell to the customer.
W.C. Holman, in "Salesmanship," says: "One cannot make others
believe what he himself believes, unless he himself is an earnest
believer. Dwight L. Moody swayed enormous audiences by the simple
power of his own wonderful earnestness. No one could listen to
Moody without saying: 'This man believes absolutely every word he
is speaking. If he feels what he says so tremendously, there must be
something in it.' If every salesman realized how largely the attitude
of the 'prospect' depended upon the salesman's own mental
attitude, he would be as careful to get into the right frame of mind
when he started out to approach a prospect as he would be to carry
a sample case. It is a simple matter for him to do this. All that is
necessary is for him to 'take account of stock' just before he starts
out—to enumerate to himself all the strong, convincing points in his
proposition—to consider the good high qualities of the goods he is
selling—run over in his mind the splendid characteristics of his house
—think of the great number of customers who have bought his
product—and of the supremely satisfying reasons why other
customers should buy his goods. In other words, before a salesman
starts to sell other men, he should sell himself. He should make this
sale to himself at the beginning of every day's work."
The student should acquaint himself thoroughly with the creative
force of Suggestion and Auto-Suggestion in Character Building, and
in producing and maintaining the proper Mental Attitude. The
volume of this series entitled "Suggestion and Auto-Suggestion"
gives both the theory, principles and methods of applying Auto-
Suggestion in the directions named. One need no longer be a slave
of his Mental Attitude. On the contrary he may create and preserve
the Mental Attitude he deems advisable and necessary at any time.
Mr. W.C. Holman, one of the best of the inspirational writers on
Salesmanship, gives the following interesting instance of the use of
Auto-Suggestion by a salesman. He says: "One of the best salesmen
the writer ever knew got up what he called his catechism. He used
to put himself through it every morning before starting out.
Oftentimes he repeated it aloud if he had the opportunity. The
questions he would repeat in a quiet tone, but the answers he would
pronounce with all the earnestness of which he was capable. His
catechism ran somewhat as follows:
"Am I working for a good house? YES!
"Has my house the reputation and prestige of being one of the
best in its line? YES!
"Have we made hundreds of thousands of sales like the sales I am
going to make to-day? YES!
"Have we an enormous body of satisfied users? YES!
"Am I selling the best goods of the kind made anywhere in the
world? YES!
"Is the price I am asking a fair one? YES!
"Do the men I am going to call on need the article I am selling?
YES!
"Do they realize that now? NO!
"Is that the very reason I am going to call on them—because at
present they don't want my goods, and haven't yet bought them?
YES!
"Am I justified in asking a prospect's time and attention to present
my proposition? BY ALL THE POWERS, YES!
"Am I going to get into the office of every man that I call on, if
there is any earthly way to do it? YES!
"Am I going to sell every man I call on to-day? YOU BET I AM!"
Referring to the above "catechism" of Mr. Holman, we would say
that if a man would work himself up to the point of asking and
answering these questions in earnest, and would carry the spirit
thereof through the day, he would render himself almost invincible.
A spirit like that is the spirit of the Light Brigade, of Napoleon, of the
Berserker Norseman who made a way for himself. Such a man would
make opportunities, instead of begging for them. Such a man would
be inspired. This is Auto-Suggestion raised to the Nth Power. Try it—
you need it in your business!
The second phase of the Pre-Approach is that of obtaining an
interview with the prospective customer, generally known as "the
prospect." In many instances the salesman is able to secure the
interview by simply walking into the presence of the prospect, the
latter being in full view in his store or office and no intermediary
being present to intercept the approach. In such cases the second
phase of the Pre-Approach is passed over, and the actual Approach
is entered into at once. But in other cases, particularly in the large
office buildings of the principal cities, the prospect is found to be in
his private office, and the salesman's advance is halted by a clerk, or
even an office boy, and there are certain preliminaries to be gone
through with before an interview may be obtained. In many cases,
"big" men (or those who wish to be considered "big") surround
themselves with so much formality and red-tape that it is quite a
feat to run the gauntlet of the guardians of the inner temple, and
much tact, diplomacy, presence of mind, and often strategy is
required of the Salesman in order that he may "get at his man."
Macbain, in his work entitled "Selling," says of this stage:
"Between the pre-approach and the actual approach sometimes lies
a trying time for the salesman. It is no uncommon thing for a
prospective customer to keep a salesman waiting, either outside the
office door and out of sight, or inside and in the presence of the
prospective buyer. This is known as 'breaking the salesman's nerve.'
It is often done with the idea of deliberately making the salesman
nervous and consequently unable to make such an approach as
otherwise would be possible. Perhaps one of the most common
forms of this is seen when the prospective customer appears to be
very busily interested in something at his desk and allows the
salesman to stand an indefinite length of time and then turns
suddenly upon him. This is especially disconcerting to the young
man, but the experienced salesman recognizes it as an indication
that either the man is very busy and actually hates to take his mind
off his work, or that he is afraid of being talked into something that
he will later regret. The salesman consequently shapes his
introduction accordingly and will in no wise be disconcerted by this
attempt as it will enable him to study carefully the outward
characteristics of the man whom he is about to approach."
In many cases this waiting is forced on the salesman by a
prospect who also knows something of the laws of psychology—for
such knowledge is not confined to the salesman by any means, the
buyer having posted himself in many cases. In the game of checkers
or draughts quite an important advantage accrues to the player
securing what is technically known as "the move," which, however, is
a very different thing from the "first play." There is in the psychology
of the sale, or of the interview between two people of equal
strength, a something which corresponds very closely with "the
move" in checkers. This something gives a decided advantage to the
person securing it, and it is worth striving for. This something is
subtle and almost indescribable, although apparent to every one
who has dealings with his fellow men. It seems to be a matter of
mental balance and poise. The salesman, if he be well balanced and
poised, is "positive" to the buyer, the latter being in a listening, and
therefore passive, attitude. So far the salesman has "the move,"
which however he may later lose if the prospect plays scientifically.
Well, to get back to the "waiting" stage, the prospect by disturbing
the salesman's poise, and "breaking his nerve" by keeping him
waiting on the anxious bench in a state of suspense, often manages
to get "the move" on him, unless he understands the psychology of
the process and accordingly avoids it. Suspense is the most nerve-
breaking mental state on the psychological list, as all realize who
have experienced it. Beware of losing "the move."
An important factor in getting past the stockade of the outer office
is the consciousness of Self Respect and the realization of the "I" of
which we have spoken. This mental attitude impresses itself upon
those who guard the outer works, and serves to clear the way. As
Pierce says: "Remember, you are asking no favors; that you have
nothing to apologize for, and that you have every reason in the world
for holding your head high. And it is wonderful what this holding up
of the head will do in the way of increasing sales. We have seen
salesmen get entrance to the offices of Broadway buyers simply
through the holding of the head straight up from the shoulders." But
it is the Mental Attitude back of the physical expression that is the
spirit of the thing—don't forget this.
The Mental Attitude and the physical expression thereof
instinctively influence the conduct of other people toward one. We
may see the same thing illustrated in the attitude and action of the
street boy toward dogs. Let some poor cur trot along with drooping
ears, timid expression, meek eyes, and tail between his legs, and the
urchin will be apt to kick him or throw a rock at his retreating form.
Note the difference when the self-respecting dog, with spirit in him,
trots past, looking the boy fearlessly in the eye and showing his
sense of self-respect and power to back it up in every movement.
That dog is treated accordingly. There are certain people whose
manner is such that they do not need to ask respect and
consideration—it is given them as a matter of right and privilege.
People stand aside to give them room, and move up in street cars
that they may have a seat. And it does not necessarily follow that
the person to whom this respect is shown is a worthy individual or a
person of fine qualities—he may be a confidence man or a swindler.
But whatever he is, or may be, he has certain outward mannerisms
and characteristics which enable him to "put up a good front" and
which carry him through. At the back of it all will be found certain
mental states which produce the genuine outward characteristics
and manner in the case of genuine instances of persons possessing
authority and high position, the confidence man merely presenting a
passable counterfeit, being a good actor.
It is often necessary for the salesman to send in a card to the
inner office. It is well for him to have some cards, well engraved in
the most approved manner, bearing simply his name: "Mr. John Jay
Jones," with his business appearing thereon. If he is travelling from
a large city, and is selling in smaller towns, he may have "New York,"
"Chicago," "Philadelphia," "Boston," etc., as the case may be in the
corner of his card. If the name of his business appears on the card
the prospect often goes over the matter of a possible sale, mentally,
without the salesman being present to present his case, and then
may decline to grant an interview. The name, without the business,
often arouses interest or curiosity and thus, instead of hindering,
really aids in securing the interview.
Regarding the discussion of the business with anyone other than
the prospect himself, the authorities differ. As a matter of fact it
would seem to depend largely upon the particular circumstances of
each case, the nature of the articles to be sold, and the character
and position of the subordinate in question.
One set of authorities hold that it is very poor policy to tell your
business to a subordinate, and that it is far better to tell him
courteously but firmly that your business is of such a nature that you
can discuss it only with the prospect in person. Otherwise, it is held
that the subordinate will tell you that the matter in question has
already been considered by his principal, and that he is fully
informed regarding the proposition, and has given orders that he is
not to be disturbed further regarding it.
The other set of authorities hold that in many cases the
subordinate may be pressed into service, by treating him with great
respect, and an apparent belief in his judgment and authority,
winning his good-will and getting him interested in your proposition,
and endeavoring to have him "speak about it" to his superior during
the day. It is claimed that a subsequent call, the day following, will
often prove successful, as the subordinate will have paved the way
for an interview and have actually done some work for you in the
way of influence and selling talk. It is held that some salesmen have
made permanent "friends in camp" of these subordinates who have
been approached in this way.
It would seem, however, as we have said, to depend much upon
the particular circumstances of the case. In some cases the
subordinate is merely a "hold-off," or "breakwater;" while in others
he is a confidential employee whose opinion has weight with the
prospect, and whose good-will and aid are well worth securing. In
any event, however, it is well to gain the respect and good-will of
those in the "outer court," for they can often do much in the way of
helping or injuring your chances. We have known cases in which
subordinates "queered" a salesman who had offended them; and we
have known other cases in which the subordinate being pleased by
the salesman "put him next." It is always better to make a friend
rather than an enemy—from the office-boy upward—on general
principles. Many a fine warrior has been tripped up by a small
pebble. Strong men have died from the bite of a mosquito.
The following advice from J.F. Gillen, the Chicago manager of the
Burroughs Adding Machine Company, is very much to the point. Mr.
Gillen, in the magazine "Salesmanship," says: "A salesman who has
not proved his mettle—and who, unfortunately, is not sure of himself
—is likely to be overcome by a sense of his own insignificance on
entering the private domain of the great man, rich man, or
influential man, from whom he hopes to get an order. The very hum
and rush of business in this boss's office are very awe-inspiring. The
fact that there exists an iron-clad rule, designed to protect the boss
against intrusion, forbidding the admittance of an uninvited
salesman—and the fact that the army of employees are bound by
this rule to oppose the entrance of any such visitor—combine to
make an untried salesman morally certain of his powerlessness; to
make him feel that he has no justifiable reason for presenting
himself at all. Indeed he has none, if the awe which he feels for red-
tape, rules, dignitaries, has made him lose sight of the attractions of
his own proposition; has swallowed up his confidence in what he has
to offer and his ability to enthuse the prospect in regard to it. * * *
If you believe that your proposition will prove interesting to the
prospect and that he will profit by doing business with you, you have
a right to feel that the rule barring salesmen from his presence was
not intended to bar you. Convince yourself of this and the stern
negative of the information clerk will not abash you. You will find
yourself endowed with a courage and resourcefulness to cope with a
slick secretary who gives glibly evasive replies when you try to find
out whether Mr. Prospect is now in his office, whether he cannot see
you at once, and what reason exists for supposing you could
possibly tell your business to any subordinate in place of him. Once
you are thus morally sure of your ground, the hardest part of the
battle is won. * * * You can see the prospect and get speech with
him, no matter what obstacles intervene, if your nerve holds out and
you use your brains."
Remember this, always: The Psychology of Salesmanship applies
not only to work with the prospect, but also to work with those who
bar the way to him. Subordinates have minds, faculties, feelings and
strong and weak points of mentality—they have their psychology just
as their employer has his. It will pay you to make a careful study of
their psychology—it has its rules, laws and principles. This is a point
often overlooked by little salesmen, but fully recognized by the "big"
ones. The short cut to the mind of many a prospect is directly
through the mind of the man in the outer office.
CHAPTER VII
THE PSYCHOLOGY OF PURCHASE
There are several stages or phases manifested by the buyer in the
mental process which results in a purchase. While it is difficult to
state a hard and fast rule regarding the same, because of the variety
of temperament, tendencies and mental habits possessed in several
degrees by different individuals, still there are certain principles of
feeling and thought manifested alike by each and every individual
buyer, and a certain logical sequence is followed by all men in each
and every original purchase. It follows, of course, that these
principles, and this sequence, will be found to be operative in each
and every original purchase, whether that purchase be the result of
an advertisement, display of goods, recommendation, or the efforts
of a salesman. The principle is the same in each and every case, and
the sequence of the mental states is the same in each and every
instance. Let us now consider these several mental states in their
usual sequence.
The several mental states manifested by every buyer in an original
purchase are given below in the order of sequence in which they are
usually manifested:—
I. Involuntary Attention.
II. First Impression.
III. Curiosity.
IV. Associated Interest.
V. Consideration.
VI. Imagination.
VII. Inclination.
VIII. Deliberation.
IX. Decision.
X. Action.
We use the term "original purchase" in this connection in order to
distinguish the original purchase from a repeated order or
subsequent purchase of the same article, in which latter instance the
mental process is far more simple and which consists merely in
recognizing the inclination, or habit, and ordering the goods, without
repeating the original complex mental operation. Let us now proceed
to a consideration of the several mental stages of the original
purchase, in logical sequence:—
I. Involuntary Attention. This mental state is the elementary phase
of attention. Attention is not a faculty of the mind, but is instead the
focusing of the consciousness upon one object to the temporary
exclusion of all other objects. It is a turning of the mind on an
object. The object of attention may be either external, such as a
person or thing; or internal, such as a feeling, thought, memory, or
idea. Attention may be either voluntary, that is, directed consciously
by the will; or involuntary, that is, directed unconsciously and
instinctively and apparently independently of the will. Voluntary
attention is an acquired and developed power and is the attribute of
the thinker, student and intellectual individual in all walks of life.
Involuntary attention, on the contrary, is but little more than a reflex
action, or a nervous response to some stimulus. As Halleck says:
"Many persons scarcely get beyond the reflex stage. Any chance
stimulus will take their attention away from their studies or their
business." Sir William Hamilton made a still finer distinction, which
is, however, generally overlooked by writers on the subject, but
which is scientifically correct and which we shall follow in this book.
He holds that there are three degrees or kinds of attention: (1) the
reflex or involuntary, which is instinctive in nature; (2) that
determined by desire or feeling, which partakes of both the
involuntary and voluntary nature, and which although partly
instinctive may be resisted by the will under the influence of the
judgment; and (3) that determined by deliberate volition in response
to reason, as in study, scientific games, rational deliberation, etc.
The first mental step of the purchase undoubtedly consists of
involuntary or reflex attention, such as is aroused by a sudden
sound, sight, or other sensation. The degree of this involuntary
attention depends upon the intensity, suddenness, novelty, or
movement of the object to which it responds. All persons respond to
the stimuli arousing this form of attention, but in different degrees
depending upon the preoccupation or concentration of the individual
at the time. The striking or novel appearance of an advertisement;
the window-display of goods; the appearance of the salesman—all
these things instinctively arouse the involuntary attention, and the
buyer "turns his mind on" them. But this turning the mind on
belongs to Hamilton's first class—that of the instinctive response to
the sight or sound, and not that aroused by desire or deliberate
thought. It is the most elemental form of attention or mental effort,
and to the salesman means simply: "Well, I see you!" Sometimes the
prospect is so preoccupied or concentrated on other things that he
barely "sees" the salesman until an added stimulus is given by a
direct remark.
II. First Impression. This mental state is the hasty generalization
resulting from the first impression of the object of attention—the
advertisement, suggestion, display of goods, or the Salesman—
depending in the last case upon the general appearance, action,
manner, etc., as interpreted in the light of experience or association.
In other words, the prospect forms a hasty general idea of the thing
or person, either favorable or unfavorable, almost instinctively and
unconsciously. The thing or person is associated or classed with
others resembling it in the experience and memory of the prospect,
and the result is either a good, bad or indifferent impression
resulting from the suggestion of association. For this reason the ad.
man and the window dresser endeavor to awaken favorable and
pleasing associated memories and suggestions, and "puts his best
foot foremost." The Salesman endeavors to do the same, and seeks
to "put up a good front" in his Approach, in order to secure this
valuable favorable first impression. People are influenced more than
they will admit by these "first impressions," or suggestions, of
appearance, manner, etc., and the man who understands psychology
places great importance upon them. A favorable first impression
smooths the way for the successful awakening of the later mental
states. An unfavorable first impression, while it may be removed and
remedied later, nevertheless is a handicap which the Salesman
should avoid.
(Note: The mental process of the purchase now passes from the
stage of involuntary attention, to that of attention inspired by desire
and feeling which partakes of both the voluntary and involuntary
elements. The first two stages of this form of attention are known as
Curiosity and Associated Interest, respectively. In some cases
Curiosity precedes, in others Associated Interest takes the lead, as
we shall see. In other cases the manifestation of the two is almost
simultaneous.)
III. Curiosity. This mental state is really a form of Interest, but is
more elemental than Associated Interest, being merely the interest
of novelty. It is the strongest item of interest in the primitive races,
in children, and in many adults of elemental development and habits
of thought. Curiosity is the form of Interest which is almost
instinctive, and which impels one to turn the attention to strange
and novel things. All animals possess it to a marked degree, as
trappers have found out to their profit. Monkeys possess it to an
inordinate degree, and the less developed individuals of the human
race also manifest it to a high degree. It is connected in some way
with the primitive conditions of living things, and is probably a
heritage from earlier and less secure conditions of living, where
inquisitiveness regarding new, novel and strange sights and sounds
was a virtue and the only means of acquiring experience and
education. At any rate, there is certainly in human nature a decided
instinctive tendency to explore the unknown and strange—the
attraction of the mysterious; the lure of the secret things; the
tantalizing call of the puzzle; the fascination of the riddle.
The Salesman who can introduce something in his opening talk
that will arouse Curiosity in the prospect has done much to arouse
his attention and interest. The street-corner fakir, and the "barker"
for the amusement-park show, understand this principle in human
nature, and appeal largely to it. They will blindfold a boy or girl, or
will make strange motions or sounds, in order to arouse the curiosity
of the crowd and to cause them to gather around—all this before the
actual appeal to interest is made. In some buyers Curiosity precedes
Associated Interest—the interest in the unknown and novel precedes
the practical interest. In others the Associated Interest—the practical
interest inspired by experience and association—precedes Curiosity,
the latter manifesting simply as inquisitiveness regarding the details
of the object which has aroused Associated Interest. In other cases,
Curiosity and Associated Interest are so blended and shaded into
each other that they act almost as one and simultaneously. On the
whole, though, Curiosity is more elemental and crude than
Associated Interest, and may readily be distinguished in the majority
of cases.
IV. Associated Interest. This mental state is a higher form of
interest than Curiosity. It is a practical interest in things relating to
one's interests in life, his weal or woe, loves or hates, instead of
being the mere interest in novelty of Curiosity. It is an acquired trait,
while Curiosity is practically an instinctive trait. Acquired Interest
develops with character, occupation, and education, while Curiosity
manifests strongly in the very beginnings of character, and before
education. Acquired Interest is manifested more strongly in the man
of affairs, education and experience, while Curiosity has its fullest
flower in the monkey, savage, young child and uncultured adult.
Recognizing the relation between the two, it may be said that
Curiosity is the root, and Associated Interest the flower.
Associated Interest depends largely upon the principle of
Association or Apperception, the latter being defined as "that mental
process by which the perceptions or ideas are brought into relation
to our previous ideas and feelings, and thus are given a new
clearness, meaning and application." Apperception is the mental
process by which objects and ideas presented to us are perceived
and thought of by us in the light of our past experience,
temperament, tastes, likes and dislikes, occupation, interest,
prejudices, etc., instead of as they actually are. We see everything
through the colored glasses of our own personality and character.
Halleck says of Apperception: "A woman may apperceive a passing
bird as an ornament to her bonnet; a fruit grower, as an insect killer;
a poet, as a songster; an artist, as a fine bit of coloring and form.
The housewife may apperceive old rags as something to be thrown
away; a ragpicker, as something to be gathered up. A carpenter, a
botanist, an ornithologist, a hunter, and a geologist walking through
a forest would not see the same things." The familiar tale of the
text-books illustrates this principle. It relates that a boy climbed up a
tree in a forest and watched the passers-by, and listened to their
conversation. The first man said: "What a fine stick of timber that
tree would make." The boy answered: "Good morning, Mr.
Carpenter." The second man said: "That is fine bark." The boy
answered: "Good morning, Mr. Tanner." The third man said: "I'll bet
there's squirrels in that tree." The boy answered: "Good morning,
Mr. Hunter." Each and every one of the men saw the tree in the light
of his personal Apperception or Associated Interest.
Psychologists designate by the term "the apperceptive mass" the
accumulated previous experiences, prejudices, temperament,
inclination and desires which serve to modify the new perception or
idea. The "apperceptive mass" is really the "character" or "human
nature" of the individual. It necessarily differs in each individual, by
reason of the great variety of experiences, temperament, education,
etc., among individuals. Upon a man's "apperceptive mass," or
character, depends the nature and degree of his interest, and the
objects which serve to inspire and excite it.
It follows then that in order to arouse, induce and hold this
Associated Interest of the prospect, the Salesman must present
things, ideas or suggestions which will appeal directly to the
imagination and feelings of the man before him, and which are
associated with his desires, thoughts and habits. If we may be
pardoned for the circular definition we would say that one's
Associated Interest is aroused only by interesting things; and that
the interesting things are those things which concern his interests. A
man's interests always interest him—and his interests are usually
those things which concern his advantage, success, personal well-
being—in short his pocketbook, social position, hobbies, tastes, and
satisfaction of his desires. Therefore the Salesman who can throw
the mental spot-light on these interesting things, may secure and
hold one's Associated Interest. Hence the psychology of the
repeated statement: "I can save you money;" "I can increase your
sales;" "I can reduce your expenses;" "I have something very
choice;" or "I can give you a special advantage," etc.
It may as well be conceded that business interest is selfish
interest, and not altruistic. In order to interest a man in a business
proposition he must be shown how it will benefit him in some way.
He is not running a philanthropic institution, or a Salesman's Relief
Fund, nor is he in business for his health—he is there to make
money, and in order to interest him you must show him something
to his advantage. And the first appeal of Associated Interest is to his
feeling of Self Interest. It must be in the nature of the mention of
"rats!" to a terrier, or "candy!" to a child. It must awaken pleasant
associations in his mind, and pleasing images in his memory. If this
effect is produced, he can be speedily moved to the succeeding
phases of Imagination and Inclination. As Halleck says: "All feeling
tends to excite desire. * * * A representative image of the thing
desired is the necessary antecedent to desire. If the child had never
seen or heard of peaches he would have no desire for them." And,
following this same figure, we may say that if the child has a taste
for peaches he will be interested in the idea of peaches. And so
when you say "peaches!" to him you have his Associated Interest,
which will result in a mental image of the fruit followed by a desire
to possess it, and he will listen to your talk regarding the subject of
"peaches."
The following are the general psychological rules regarding
Associated Interests:
I. Associated Interest attaches only to interesting things—that is
to things associated with one's general desires and ideas.
II. Associated Interest will decline in force and effect unless some
new attributes or features are presented—it requires variety in
presentation of its object.
Macbain says: "One of the old time salesmen who used to sell the
trade in the Middle West, beginning some thirty years ago, and
following that vocation for several decades, used as his motto, 'I am
here to do you good.' He did not make his statement general, either,
in telling his customers how he could do it. He got right down to the
vital affairs which touched his customers. He demonstrated it to
them, and this personal demonstration is the kind that makes the
sales."
Remember, always, that the phase of Associated Interest in a
purchase is not the same as the phase of Demonstration and Proof.
It is the "warming up" process, preceding the actual selling talk. It is
the stage of "thawing out" the prospect and melting the icy covering
of prejudice, caution and reluctance which encases him. Warm up
your prospect by general statements of Associated Interest, and
blow the coals by positive, brief, pointed confident statements of the
good things you have in store for him. And, finally, remember that
the sole purpose of your efforts at this state is to arouse in him the
mental state of INTERESTED EXPECTANT ATTENTION! Keep blowing
away at this spark until you obtain the blaze of Imagination and the
heat of Desire.
V. Consideration. This mental state is defined as: "An examination,
inquiry, or investigation into anything." It is the stage following
Curiosity and Associated Interest, and tends toward an inquiry into
the thing which has excited these feelings. Consideration, of course,
must be preceded and accompanied by Interest. It calls for the
phase of Attention excited by feeling, but a degree of voluntary
attention is also manifested therewith. It is the "I think I will look
into this matter" stage of the mental process of purchase. It is
usually evidenced by a disposition to ask questions regarding the
proposition, and to "see what there is to it, anyway." In
Salesmanship, this stage of Consideration marks the passing from
the stage of Approach on the Salesman's part, to that of the
Demonstration. It marks the passage from Passive Interest to Active
Interest—from the stage of being "merely interested" in a thing, to
that of "interested investigation." Here is where the real selling work
of the salesman begins. Here is where he begins to describe his
proposition in detail, laying stress upon its desirable points. In the
case of an advertisement, or a window display, the mental operation
goes on in the buyer's mind in the same way, but without the
assistance of the salesman. The "selling talk" of the advertisement
must be stated or suggested by its text. If the Consideration is
favorable and reveals sufficiently strong attractive qualities in the
proposition or article, the mind of the buyer passes on to the next
stage of the process which is known as:
VI. Imagination. This mental state is defined as: "The exercise of
that power or faculty of the mind by which it conceives and forms
ideal pictures of things communicated to it by the organs of sense."
In the mental process of a purchase, the faculty of imagination takes
up the idea of the object in which the Associated Interest has been
aroused, and which has been made the subject of Consideration,
and endeavors to picture the object in use and being employed in
different ways, or as in possession of the buyer. One must use his
imagination in order to realize what good a thing will be to him; how
he may use it; how it will look; how it will sell; how it will serve its
purpose; how it will "work out" or "make good" when purchased. A
woman gazing at a hat will use her imagination to picture how she
will look in it. The man looking at the book will use his imagination in
picturing its uses and the pleasure to be derived therefrom. The
business man will use his imagination to picture the probable sale of
the goods, their display, their adaptability to his trade, etc. Another
will picture himself enjoying the gains from his purchase.
Imagination plays an important part in the psychology of the sale. It
is the direct inciter of desire and inclination. The successful salesman
realizes this, and feeds the flame of the imagination with the oil of
Suggestion. In fact, Suggestion receives its power through the
Imagination. The Imagination is the channel through which
Suggestion reaches the mind. Salesmen and ad. writers strive to
arouse the imagination of their prospective customers by clever
word-painting. The Imagination is the "direct wire" to Desire. From
Imagination it is a short step to the next mental stage which is
called:
VII. Inclination. This mental state is defined as: "A leaning or bent
of the mind or will; desire; propensity." It is the "want to" feeling. It
is the mental state of which Desire is an advanced stage. Inclination
has many degrees. From a faint inclination or bent in a certain
direction, it rises in the scale until it becomes an imperious demand,
brooking no obstacle or hindrance. Many terms are employed to
designate the various stages of Inclination, as for instance: Desire,
wish, want, need, inclination, leaning, bent, predilection, propensity,
penchant, liking, love, fondness, relish, longing, hankering,
aspiration, ambition, appetite, hunger, passion, craving, lust, etc.
Desire is a strange mental quality, and one very difficult to define
strictly. It is linked with feeling on one side, and with will on the
other. Feeling rises to desire, and desire rises to the phase of will
and endeavors to express itself in action. Halleck says of Desire: "It
has for its object something which will bring pleasure or get rid of
pain, immediate or remote, for the individual or for some one in
whom he is interested. Aversion, or a striving to get away from
something, is merely the negative aspect of desire." Inclination in its
various stages is aroused through the appeals to the feelings
through the imagination. The feelings related to the several faculties
are excited into action by a direct appeal to them through the
imagination, and inclination or desired results. Appeal to
Acquisitiveness will result in a feeling which will rise to inclination
and desire for gain. Appeal to Approbativeness will act likewise in its
own field. And so on through the list, each well-developed faculty
being excited to feeling by the appropriate appeal through the
imagination, and thus giving rise to Inclination which in turn strives
to express itself in action through the will.
In short, every man is a bundle of general desires, the nature and
extent of which are indicated by his several faculties, and which
result from heredity, environment, training, experience, etc. These
desires may be excited toward a definite object by the proper
emotional appeal through the imagination, and by suggestion. Desire
must be created or aroused before action can be had, or the will
manifest in action. For, at the last, we do things only because we
"want to," directly or indirectly. Therefore, the important aim of the
Salesman is to make his prospect "want to." And in order to make
him "want to" he must make him see that his proposition is
calculated to "bring pleasure, or get rid of pain, immediate or
remote, for the individual or for someone else in whom he is
interested." In business, the words "profit and loss" may be
substituted for "pleasure and pain," although really, they are but
forms of the latter. But even when the prospect is brought to the
stage of strong inclination or desire, he does not always move to
gratify the same. Why is this? What other mental process interferes?
Let us see as we pass on to the next stage of the purchase, known
as:
VIII. Deliberation. This mental state is defined as: "The act of
deliberating and weighing facts and arguments in the mind, calmly
and carefully." Here is manifested the action of thought and reason
—the mental process of weighing and balancing facts, feelings, and
inclinations. For it is not only facts and proofs which are weighed in
the mental balance, but also feelings, desires, and fears. Pure logical
reasoning inclines to strict logical processes based upon irrefragible
facts, it is true—but there is but little pure logical reasoning. The
majority of people are governed more by their feelings and
inclinations—their loves and their fears—than by logic. It has been
said: "People seek not reasons, but excuses for following their
feelings." The real deliberation, in the majority of cases, is the
weighing of probable advantages and disadvantages—of various
likes and dislikes—of hopes and fears.
It is said that our minds are controlled by motives—and the
strongest motive wins. We often find that when we think we desire a
thing ardently, we then find that we also like something else better,
or perhaps fear something else more than we desire the first thing.
In such case, the strongest or most pressing feeling wins the day.
The faculties here exert their different influences. Caution opposes
Acquisitiveness. Acquisitiveness opposes Conscientiousness. Fear
opposes Firmness. And so on. The deliberation is not only the
weighing of facts, but also the weighing of feelings.
The process of Deliberation—the weighing of desires—the play
and counterplay of motives—is well illustrated by a scene in a
classical French comedy. "Jeppe," one of the characters, has been
given money by his wife to buy her a cake of soap. He prefers to
buy a drink with the coin, for his inclinations tend in that direction.
But he knows that his wife will beat him if he so squanders the
money. He deliberates over the pleasure to be derived from the
drink, and the pain which would arise from the beating. "My
stomach says drink—my back says soap," says Jeppe. He deliberates
further. Then: "My stomach says Yes! My back says No!" cries the
poor wight. The conflict between back and stomach rages still more
fiercely. Then comes the deciding point: "Is not my stomach more to
me than my back? Sure, it is! I say Yes!" cries Jeppe. And away to
the tavern he marches. It has been remarked that if the active
suggestion of the distant sight of his wife armed with the cudgel,
had been added to the situation, Jeppe would have bought the soap.
Or, if the tavern had not been so handy, the result might have been
different. Sometimes a mental straw tips the scale. The above
illustration contains the entire philosophy of the action of the mind in
the process of Deliberation. The salesman will do well to remember
it.
Halleck thus well states the immediate and remote factors in
choice: "The immediate factors are * * * (1) a preceding process of
desire; (2) the presence in consciousness of more than one
represented object or end, to offer an alternative course of action;
(3) deliberation concerning the respective merits of these objects;
(4) the voluntary fiat of decision, which seems to embody most the
very essence of will. The remote factors are extremely difficult to
select. The sum total of the man is felt more in choice than
anywhere else. * * * Before a second person could approximate the
outcome, he would have to know certain remote factors, the
principal being: (1) heredity; (2) environment; (3) education; (4)
individual peculiarities." This eminent authority might well have
added an additional element—a most important one—as follows: (5)
SUGGESTION.
The Salesman watching carefully the shifting scale of Deliberation,
injects a telling argument or suggestion into the scale, which gives
weight to his side at a critical stage. He does this in many ways. He
may neutralize an objection by a counter-fact. He adds another
proof or fact here—a little more desire and feeling there, until he
brings down the scale to a decision. It must be remembered that
this Deliberation is not regarding the desirability of the proposition—
the prospect has admitted his desire, either directly or indirectly, and
is now engaged in trying to justify his desire by reason and
expediency. He is seeking for reasons or "excuses" to back up his
desire, or perhaps, is endeavoring to strike a balance of his
conflicting desires and feelings. His mental debate is not over the
question of desiring the goods, but over the expediency and
probable result of buying them. It is the "to buy or not to buy"
stage. This is a delicate part of the process of the purchase, and
many prospects act like "see-saws" during the process. The clever
Salesman must be ready with the right argument at the right place.
To him this is the Argumentive Stage. Finally, if the Salesman's
efforts are successful, the balance drops, and the process passes to
the next stage, known as—
IX. Decision. This mental stage is defined as: "The mental act of
deciding, determining, or settling any point, question, difference, or
contest." It is the act of the will, settling the dispute between the
warring faculties, feelings, ideas, desires and fears. It is will acting
upon reason, or (alas! too often, upon mere feeling). Without
entering into a metaphysical discussion, let us remind you that the
practical psychology of the day holds that "the strongest motive at
the moment wins the choice." This strongest motive may be of
reason or of feeling; conscious or unconscious; but strongest at that
moment it must be, or it would not win. And this strongest motive is
strongest merely because of our character or "nature" as manifested
at that particular moment, in that particular environment, under the
particular circumstances, and subject to the particular suggestions.
The choice depends more upon association than we generally
realize, and association is awakened by suggestion. As Halleck says:
"It is not the business of the psychologist to state what power the
association of ideas ought to have. It is for him to ascertain what
power it does have." And as Ziehen says: "We cannot think as we
will, but we must think just as those associations which happen to
be present prescribe." This being the case, the Salesman must
realize that the Decision is based always upon (1) the mental states
of the man at that moment; plus (2) the added motives supplied by
the Salesman. It is "up to" the Salesman to supply those motives,
whether they be facts, proofs, appeals to reason, or excitement of
feeling. Hope, fear, like, dislike—these are the potent motives in
most cases. In business, these things are known as "profit or loss."
All the faculties of the mind supply motives which aroused may be
thrown into the balance affecting decision. This is what argument,
demonstration and appeal seek to do—supply motives.
(Note:—It might naturally be supposed that when the final stage
of Decision has been reached, the mental process of purchase is at
an end. But, not so. Will has three phases: Desire, Decision, and
Action. We have passed through the first two, but Action still is
unperformed. A familiar example is that of the man in bed in the
morning. He ponders over the question of rising, and finally decides
to get up. But action does not necessarily result. The trigger of
Action has not been pulled, and the spring released. So thus we
have another mental state, known as:—)
X. Action. This mental state is defined as: "Volition carried into
effect." Mill says: "Now what is an action? Not one, but a series of
two things: the state of mind called a volition, followed by an effect.
The volition or intention to produce the effect is one thing; the effect
produced in consequence of the intention is another thing; the two
together constitute the action." Halleck says: "For a completed act of
will, there must be action along the line of the decision. Many a
decision has not aroused the motor centers to action, nor quickened
the attention, for any length of time. There are persons who can
frame a dozen decisions in the course of a morning, and never carry
out one of them. Sitting in a comfortable chair, it may take one but a
very short time to form a decision that will require months of hard
work. * * * Some persons can never seem to understand that
resolving to do a thing is not the same as doing it. * * * There may
be desire, deliberation, and decision; but if these do not result in
action along the indicated line, the process of will is practically
incomplete." Many a person decides to do a thing but lacks the
something necessary to release the motive impulses. They tend to
procrastinate, and delay the final act. These people are sources of
great care and work to the Salesman. Some men can get their
prospects to the deciding point, but fail to get them to act. Others
seem specially adapted to "closing" these cases. It requires a
peculiar knack to "close"—the effort is entirely psychological. We
shall consider it in a subsequent chapter under the head of
"Closing." To be a good "closer" is the ambition of every Salesman,
for it is the best paid branch of his profession. It depends largely
upon the scientific application of suggestion. To lead a prospect to
Action, is to pull the trigger of his will. To this end all the previous
work has been directed. Its psychology is subtle. What makes you
finally get out of bed in the morning, after having "decided to"
several times without resulting action? To understand this, is to
understand the process of the final Action in the mind of the buyer.
Is it not worth learning?
In the succeeding chapters we shall consider the several stages of
the "Salesman's Progress" toward a sale—the Approach, the
Demonstration, and the Closing. In these stages of the Salesman,
we shall see the action and reaction upon the Mind of the Buyer,
along the lines of the Psychology of the Purchase. In the Sale-
Purchase the minds of the Salesman and the Buyer meet. The result
is the Signed Order. The psychological process of the Sale is akin to
the progress of a game of chess or checkers. And neither is the
result of chance—well defined principles underlie each, and
established methods are laid down for the student.
Welcome to our website – the perfect destination for book lovers and
knowledge seekers. We believe that every book holds a new world,
offering opportunities for learning, discovery, and personal growth.
That’s why we are dedicated to bringing you a diverse collection of
books, ranging from classic literature and specialized publications to
self-development guides and children's books.
More than just a book-buying platform, we strive to be a bridge
connecting you with timeless cultural and intellectual values. With an
elegant, user-friendly interface and a smart search system, you can
quickly find the books that best suit your interests. Additionally,
our special promotions and home delivery services help you save time
and fully enjoy the joy of reading.
Join us on a journey of knowledge exploration, passion nurturing, and
personal growth every day!
ebookbell.com

Java Software Structures Designing And Using Data Structures 3rd Edition John Lewis

  • 1.
    Java Software StructuresDesigning And Using Data Structures 3rd Edition John Lewis download https://ebookbell.com/product/java-software-structures-designing- and-using-data-structures-3rd-edition-john-lewis-2614256 Explore and download more ebooks at ebookbell.com
  • 2.
    Here are somerecommended products that we believe you will be interested in. You can click the link to download. Java Software Structures Designing And Using Data Structures 4th Edition International Edition Lewis https://ebookbell.com/product/java-software-structures-designing-and- using-data-structures-4th-edition-international-edition-lewis-21976872 Java 19 More Algorithms And Data Structures Software Development Poul Klausen https://ebookbell.com/product/java-19-more-algorithms-and-data- structures-software-development-poul-klausen-47502928 Java 18 Algorithms And Data Structures Software Development No Isbn Poul Klausen https://ebookbell.com/product/java-18-algorithms-and-data-structures- software-development-no-isbn-poul-klausen-47502932 Java Software And Embedded Systems 1st Edition Mattis Hayes Isaiah Johansen https://ebookbell.com/product/java-software-and-embedded-systems-1st- edition-mattis-hayes-isaiah-johansen-51764284
  • 3.
    Java Software SolutionsFor Ap Computer Science 3rd Edition Loftus https://ebookbell.com/product/java-software-solutions-for-ap-computer- science-3rd-edition-loftus-21354562 Java Software Solutions Foundations Of Program Design 7th Edition 7th Edition John Lewis https://ebookbell.com/product/java-software-solutions-foundations-of- program-design-7th-edition-7th-edition-john-lewis-2371348 Java Software Solutions Global Edition 8th Edition John Lewis https://ebookbell.com/product/java-software-solutions-global- edition-8th-edition-john-lewis-30066712 Java Software Solutions 9th Edition John Lewis William Loftus https://ebookbell.com/product/java-software-solutions-9th-edition- john-lewis-william-loftus-33941204 Java Software Solutions 8th Edition 8th Edition Lewis John https://ebookbell.com/product/java-software-solutions-8th-edition-8th- edition-lewis-john-55557960
  • 6.
    java S O FT WA R E S T R U C T U R E S Third Edition ™ Designing and Using Data Structures
  • 7.
  • 8.
    java S O FT WA R E S T R U C T U R E S Third Edition Designing and Using Data Structures Addison-Wesley New York Boston San Francisco London Toronto Sydney Tokyo Singapore Madrid Mexico City Munich Paris Cape Town Hong Kong Montreal JOHN LEWIS Virginia Tech JOSEPH CHASE Radford University ™
  • 9.
    Editor-in-Chief Michael Hirsch EditorialAssistant Stephanie Sellinger Managing Editor Jeffrey Holcomb Production Supervisor Heather McNally Marketing Manager Erin Davis Marketing Coordinator Kathryn Ferranti Senior Manufacturing Buyer Carol Melville Online Product Manager Bethany Tidd Art Director Linda Knowles Cover Design Elena Sidorova Project Management, Composition, and Illustrations Nesbitt Graphics, Inc. Project Coordinator, Nesbitt Graphics, Inc. Harry Druding Project Manager, Nesbitt Graphics, Inc. Kathy Smith Text Design, Nesbitt Graphics, Inc. Jerilyn Bockorick, Alisha Webber Cover Image Steve Cole/Getty Images Access the latest information about Addison-Wesley Computer Science titles from our World Wide Web site: http://www.pearsonhighered.com/cs. Many of the designations used by manufacturers and sellers to distinguish their products are claimed as trademarks. Where those designations appear in this book, and Addison-Wesley was aware of a trademark claim, the designations have been printed in initial caps or all caps. The programs and applications presented in this book have been included for their instructional value. They have been tested with care, but are not guaranteed for any particular purpose. The publisher does not offer any warranties or representations, nor does it accept any liabilities with respect to the programs or applications. Library of Congress Cataloging-in-Publication Data Lewis, John, 1963- Java software structures : designing and using data structures / John Lewis, Joseph Chase. -- 3rd ed. p. cm. Includes bibliographical references and index. ISBN 978-0-13-607858-6 (alk. paper) 1. Java (Computer program language) 2. Data structures (Computer science) 3. Computer software--Development. I. Chase, Joseph. II. Title. QA76.73.J38L493 2009 005.13'3--dc22 2009000302 Copyright © 2010 Pearson Education, Inc. All rights reserved. No part of this publication may be reproduced, stored in a retrieval system, or transmitted, in any form or by any means, electronic, mechanical, photocopying, recording, or otherwise, without the prior written permission of the publisher. Printed in the United States of America. For information on obtaining permission for use of material in this work, please submit a written request to Pearson Education, Inc., Rights and Contracts Department, 501 Boylston Street, Suite 900, Boston, MA 02116, fax your request to (617)671-3447, or e-mail at http://www.pearsoned.com/legal/permissions.htm. Addison Wesley is an imprint of www.pearsonhighered.com ISBN-13: 978-013-607858-6 ISBN-10: 0-13-607858-3 1 2 3 4 5 6 7 8 10–EB–13 12 11 10 09
  • 10.
    To my wifeSharon and my kids: Justin, Kayla, Nathan, and Samantha –J. L. To my loving wife Melissa for her support and encouragement and to our families, friends, colleagues, and students who have provided so much support and inspiration through the years. –J. C.
  • 11.
  • 12.
    Preface vii This book isdesigned to serve as a text for a course on data structures and algo- rithms. This course is typically referred to as the CS2 course because it is often taken as the second course in a computing curriculum. We have designed this book to embrace the tenets of Computing Curricula 2001 (CC2001). Pedagogically, this book follows the style and approach of the leading CS1 book Java Software Solutions: Foundations of Program Design, by John Lewis and William Loftus. Our book uses many of the highly regarded features of that book, such as the Key Concept boxes and complete code examples. Together, these two books support a solid and consistent approach to either a two-course or three-course introductory sequence for computing students. That said, this book does not assume that students have used Java Software Solutions in a previ- ous course. Material that might be presented in either course (such as recursion or sorting) is presented in this book as well. We also include strong reference material pro- viding an overview of object-oriented concepts and how they are realized in Java. We understand the crucial role that the data structures and algorithms course plays in a curriculum and we think this book serves the needs of that course well. The Third Edition We have made some key modifications in this third edition to enhance its peda- gogy. The most important change is a fundamental reorganization of material that is designed to create a cleaner flow of topics. Instead of having an early, large chapter to review object-oriented concepts, we’ve included that material as an appendix for reference. Then we review concepts as needed and appropriate in the context of the implementation strategies discussed throughout the book and cite the appropriate reference material. This not only links the topics in a timely fash- ion but also demonstrates the usefulness of particular language constructs. We’ve expanded the discussion of Analysis of Algorithms, and given it its own chapter. The discussion, however, stays at an appropriately moderate level. Our strategy is to motivate the concepts involved in the analysis of algorithms, laying a solid foundation, rather than get embroiled in too much formality. Another key organizational change is that the introduction to collections uses a stack as the primary example. In previous editions of this book we went out of
  • 13.
    viii PREFACE our wayto introduce collections in an abstract way that separated it from the core data structures, using examples such as a bag or set collection. This new approach capitalizes on the fact that a stack is conceptually about as straightforward as it gets. Using it as a first example enhances the understanding of collections as a whole. The previous edition of the book had several chapters that focused on larger case studies that made use of collections to solve non-trivial problems. While many instructors found these useful, they also seemed to interrupt the flow of cov- erage of core topics. Therefore we have taken the case study chapters out of the book and put them on the web as supplementary resources. We encourage all instructors to download and use these resources as they see fit. Finally, for this edition we’ve reviewed and improved the discussions through- out the book. We’ve expanded the discussion of graphs and reversed the order of the graphs and hashing chapters to make a cleaner flow. And we’ve added a chap- ter that specifically covers sets and maps. We think these modifications build upon the strong pedagogy established by previous editions and give instructors more opportunity and flexibility to cover topics as they choose. Our Approach Books of this type vary greatly in their overall approach. Our approach is founded on a few important principles that we fervently embraced. First, we present the various collections explored in the book in a consistent manner. Second, we emphasize the importance of sound software design techniques. Third, we organ- ized the book to support and reinforce the big picture: the study of data structures and algorithms. Let’s examine these principles further. Consistent Presentation When exploring a particular type of collection, we carefully address each of the following issues in order: 1. Concept: We discuss the collection conceptually, establishing the services it provides (its interface). 2. Use: We explore examples that illustrate how the particular nature of the collection, no matter how it’s implemented, can be useful when solving problems. 3. Implementation: We explore various implementation options for the collection. 4. Analysis: We compare and contrast the implementations.
  • 14.
    PREFACE ix The JavaCollections API is included in the discussion as appropriate. If there is support for a particular collection type in the API, we discuss it and its imple- mentation. Thus we embrace the API, but are not completely tied to it. And we are not hesitant to point out its shortcomings. The analysis is kept at a high level. We establish the concept of Big-Oh nota- tion in Chapter 2 and use it throughout the book, but the analysis is more intu- itive than it is mathematical. Sound Program Design Throughout the book, we keep sound software engineering practices a high pri- ority. Our design of collection implementations and the programs that use them follow consistent and appropriate standards. Of primary importance is the separation of a collection’s interface from its under- lying implementation. The services that a collection provides are always formally defined in a Java interface. The interface name is used as the type designation of the collection whenever appropriate to reinforce the collection as an abstraction. In addition to practicing solid design principles, we stress them in the discus- sion throughout the text. We attempt to teach both by example and by continual reinforcement. Clean Organization The contents of the book have been carefully organized to minimize distracting tangents and to reinforce the overall purpose of the book. The organization sup- ports the book in its role as a pedagogical exploration of data structures and algo- rithms as well as its role as a valuable reference. The book can be divided into numerous parts: Part I consists of the first two chapters and provides an introduction to the concept of a collection and analysis of algorithms. Part II includes the next four chapters, which cover introductory and underlying issues that affect all aspects of data structures and algorithms as well as linear collections (stacks, queues, and lists). Part III covers the concepts of recursion, sorting, and searching. Part IV covers the nonlinear collections (trees, heaps, hashing, and graphs). Each type of collection, with the exception of trees, is covered in its own chapter. Trees are covered in a series of chapters that explore their various aspects and purposes. Chapter Breakdown Chapter 1 (Introduction) discusses various aspects of software quality and pro- vides an overview of software development issues. It is designed to establish the
  • 15.
    x PREFACE appropriate mindsetbefore embarking on the details of data structure and algo- rithm design. Chapter 2 (Analysis of Algorithms) lays the foundation for determining the efficiency of an algorithm and explains the important criteria that allow a devel- oper to compare one algorithm to another in proper ways. Our emphasis in this chapter is understanding the important concepts more than getting mired in heavy math or formality. Chapter 3 (Collections) establishes the concept of a collection, stressing the need to separate the interface from the implementation. It also conceptually intro- duces a stack, then explores an array-based implementation of a stack. Chapter 4 (Linked Structures) discusses the use of references to create linked data structures. It explores the basic issues regarding the management of linked lists, and then defines an alternative implementation of a stack (introduced in Chapter 3) using an underlying linked data structure. Chapter 5 (Queues) explores the concept and implementation of a first-in, first- out queue. Radix sort is discussed as an example of using queues effectively. The implementation options covered include an underlying linked list as well as both fixed and circular arrays. Chapter 6 (Lists) covers three types of lists: ordered, unordered, and indexed. These three types of lists are compared and contrasted, with discussion of the operations that they share and those that are unique to each type. Inheritance is used appropriately in the design of the various types of lists, which are imple- mented using both array-based and linked representations. Chapter 7 (Recursion) is a general introduction to the concept of recursion and how recursive solutions can be elegant. It explores the implementation details of recursion and discusses the basic idea of analyzing recursive algorithms. Chapter 8 (Sorting and Searching) discusses the linear and binary search algo- rithms, as well as the algorithms for several sorts: selection sort, insertion sort, bubble sort, quick sort, and merge sort. Programming issues related to searching and sorting, such as using the Comparable interface as the basis of comparing objects, are stressed in this chapter. Searching and sorting that are based in par- ticular data structures (such as heap sort) are covered in the appropriate chapter later in the book. Chapter 9 (Trees) provides an overview of trees, establishing key terminology and concepts. It discusses various implementation approaches and uses a binary tree to represent and evaluate an arithmetic expression. Chapter 10 (Binary Search Trees) builds off of the basic concepts established in Chapter 9 to define a classic binary search tree. A linked implementation of a binary search tree is examined, followed by a discussion of how the balance in the
  • 16.
    PREFACE xi tree nodesis key to its performance. That leads to exploring AVL and red/black implementations of binary search trees. Chapter 11 (Priority Queues and Heaps) explores the concept, use, and imple- mentations of heaps and specifically their relationship to priority queues. A heap sort is used as an example of its usefulness as well. Both linked and array-based implementations are explored. Chapter 12 (Multi-way Search Trees) is a natural extension of the discussion of the previous chapters. The concepts of 2-3 trees, 2-4 trees, and general B-trees are examined and implementation options are discussed. Chapter 13 (Graphs) explores the concept of undirected and directed graphs and establishes important terminology. It examines several common graph algo- rithms and discusses implementation options, including adjacency matrices. Chapter 14 (Hashing) covers the concept of hashing and related issues, such as hash functions and collisions. Various Java Collections API options for hashing are discussed. Chapter 15 (Sets and Maps) explores these two types of collections and their importance to the Java Collections API. Appendix A (UML) provides an introduction to the Unified Modeling Language as a reference. UML is the de facto standard notation for representing object-oriented systems. Appendix B (Object-Oriented Design) is a reference for anyone needing a review of fundamental object-oriented concepts and how they are accomplished in Java. Included are the concepts of abstraction, classes, encapsulation, inheri- tance, and polymorphism, as well as many related Java language constructs such as interfaces. Supplements The following supplements are available to all readers of this book at www.aw .com/cssupport. ■ Source Code for all programs presented in the book ■ Full case studies of programs that illustrate concepts from the text, includ- ing a Black Jack Game, a Calculator, a Family Tree Program, and a Web Crawler The following instructor supplements are only available to qualified in- structors at Pearson Education’s Instructor Resource Center, http://www .pearsonhighered.com/irc. Please visit the Web site, contact your local Pearson Education Sales Representative, or send an e-mail to computing@pearson.com, for information about how to access them.
  • 17.
    xii PREFACE ■ Solutionsfor selected exercises and programming projects in the book ■ Test Bank, containing questions that can be used for exams ■ PowerPoint® Slides for the presentation of the book content Acknowledgements First and most importantly we want to thank our students for whom this book is written and without whom it never could have been. Your feedback helps us become better educators and writers. Please continue to keep us on our toes. We would like to thank all of the reviewers listed below who took the time to share their insight on the content and presentation of the material in this book and its previous editions. Your input was invaluable. Mary P. Boelk, Marquette University Robert Burton, Brigham Young University Gerald Cohen, St. Joseph’s College Robert Cohen, University of Massachusetts–Boston Jack Davis, Radford University Bob Holloway, University of Wisconsin–Madison Nisar Hundewale, Georgia State University Chung Lee, California State Polytechnic University Mark C. Lewis, Trinity University Mark J. Llewellyn, University of Central Florida Ronald Marsh, University of North Dakota Eli C. Minkoff, Bates College; University of Maine–Augusta Ned Okie, Radford University Manuel A. Perez-Quinones, Virginia Tech Moshe Rosenfeld University of Washington Salam Salloum, California State Polytechnic University–Pomona Don Slater, Carnegie Mellon University Ashish Soni, University of Southern California Carola Wenk, University of Texas–San Antonio The folks at Addison-Wesley have gone to great lengths to support and develop this book along with us. It is a true team effort. Editor-in-Chief Michael Hirsch and his assistant Stephanie Sellinger have always been there to help. Marketing Manager Erin Davis, her assistant Kathryn Ferranti, and the entire Addison-Wesley sales force work tirelessly to make sure that instructors under- stand the goals and benefits of the book. Heather McNally flawlessly handled the production of the book, and Elena Sidorova is to be credited for the won- derful cover design. They are supported by Kathy Smith and Harry Druding at Nesbitt Graphics. Carol Melville always finds a way to get us time on press so
  • 18.
    PREFACE xiii that ourbook makes it into your hands in time to use it in class. Thank you all very much for all your hard work and dedication to this book. We’d be remiss if we didn’t acknowledge the wonderful contributions of the ACM Special Interest Group on Computer Science Education. Its publications and conferences are crucial to anyone who takes the pedagogy of computing seriously. If you’re not part of this group, you’re missing out. Finally, we want to thank our families, who support and encourage us in what- ever projects we find ourselves diving into. Ultimately, you are the reason we do what we do.
  • 19.
  • 20.
    Contents xv Preface Chapter 1 Introduction1 1.1 Software Quality 2 Correctness 3 Reliability 3 Robustness 4 Usability 4 Maintainability 5 Reusability 5 Portability 6 Efficiency 6 Quality Issues 6 1.2 Data Structures 7 A Physical Example 7 Containers as Objects 10 Chapter 2 Analysis of Algorithms 13 2.1 Algorithm Efficiency 14 2.2 Growth Functions and Big-OH Notation 15 2.3 Comparing Growth Functions 17 2.4 Determining Time Complexity 19 Analyzing Loop Execution 19 Nested Loops 20 Method Calls 21 Chapter 3 Collections 27 3.1 Introduction to Collections 28 Abstract Data Types 29 The Java Collections API 31
  • 21.
    xvi CONTENTS 3.2 AStack Collection 31 3.3 Crucial OO Concepts 33 Inheritance 34 Class Hierarchies 36 The Object Class 37 Polymorphism 38 References and Class Hierarchies 38 Generics 40 3.4 A Stack ADT 41 Interfaces 41 3.5 Using Stacks: Evaluating Postfix Expressions 44 3.6 Exceptions 51 Exception Messages 52 The try Statement 53 Exception Propagation 54 3.7 Implementing a Stack: With Arrays 55 Managing Capacity 56 3.8 The ArrayStack Class 57 The Constructors 58 The push Operation 59 The pop Operation 61 The peek Operation 62 Other Operations 63 Chapter 4 Linked Structures 71 4.1 References as Links 72 4.2 Managing Linked Lists 74 Accessing Elements 74 Inserting Nodes 75 Deleting Nodes 76 Sentinel Nodes 77 4.3 Elements Without Links 78 Doubly Linked Lists 78 4.4 Implementing a Stack: With Links 79 The LinkedStack Class 79
  • 22.
    CONTENTS xvii The pushOperation 83 The pop Operation 85 Other Operations 86 4.5 Using Stacks: Traversing a Maze 86 4.6 Implementing Stacks: The java.util.Stack Class 93 Unique Operations 93 Inheritance and Implementation 94 Chapter 5 Queues 99 5.1 A Queue ADT 100 5.2 Using Queues: Code Keys 103 5.3 Using Queues: Ticket Counter Simulation 107 5.4 Implementing Queues: With Links 112 The enque Operation 114 The dequeue Operation 115 Other Operations 117 5.5 Implementing Queues: With Arrays 117 The enqueue Operation 123 The dequeue Operation 124 Other Operations 125 Chapter 6 Lists 131 6.1 A List ADT 132 Iterators 134 Adding Elements to a List 135 Interfaces and Polymorphism 137 6.2 Using Ordered Lists: Tournament Maker 140 6.3 Using Indexed Lists: The Josephus Problem 150 6.4 Implementing Lists: With Arrays 152 The remove Operation 155 The contains Operation 157 The iterator Operation 158 The add Operation for an Ordered List 158
  • 23.
    xviii CONTENTS Operations Particularto Unordered Lists 161 The addAfter Operation for an Unordered List 162 6.5 Implementing Lists: With Links 163 The remove Operation 163 Doubly Linked Lists 165 The iterator Operation 168 6.6 Lists in the Java Collections API 171 Cloneable 172 Serializable 172 RandomAccess 172 Java.util.Vector 173 Java.util.ArrayList 173 Java.util.LinkedList 176 Chapter 7 Recursion 185 7.1 Recursive Thinking 186 Infinite Recursion 186 Recursion in Math 187 7.2 Recursive Programming 188 Recursion versus Iteration 190 Direct versus Indirect Recursion 191 7.3 Using Recursion 192 Traversing a Maze 192 The Towers of Hanoi 197 7.4 Analyzing Recursive Algorithms 201 Chapter 8 Sorting and Searching 209 8.1 Searching 210 Static Methods 211 Generic Methods 211 Linear Search 212 Binary Search 213 Comparing Search Algorithms 216 8.2 Sorting 217 Selection Sort 220 Insertion Sort 222
  • 24.
    CONTENTS xix Bubble Sort224 Quick Sort 226 Merge Sort 229 8.3 Radix Sort 231 Chapter 9 Trees 241 9.1 Trees 242 Tree Classifications 243 9.2 Strategies for Implementing Trees 245 Computational Strategy for Array Implementation of Trees 245 Simulated Link Strategy for Array Implementation of Trees 246 Analtsis of Trees 247 9.3 Tree Traversals 248 Preorder Traversal 248 Inorder Traversal 249 Postorder Traversal 249 Level-Order Traversal 250 9.4 A Binary Tree ADT 251 9.5 Using Binary Trees: Expression Trees 255 9.6 Implementing Binary Trees with Links 262 The find Method 269 The iteratorInOrder Method 270 9.7 Implementing Binary Trees with Arrays 271 The find Method 273 The iteratorInOrder Method 274 Chapter 10 Binary Search Trees 281 10.1 A Binary Search Tree 282 10.2 Implementing Binary Search Trees: With Links 284 The addElement Operation 286 The removeElement Operation 288
  • 25.
    xx CONTENTS The removeAllOccurrencesOperation 291 The removeMin Operation 292 10.3 Implementing Binary Search Trees: With Arrays 294 The addElement Operation 295 The removeElement Operation 296 The removeAllOccurrences Operation 302 The removeMin Operation 303 10.4 Using Binary Search Trees: Implementing Ordered Lists 304 Analysis of the BinarySearchTreeList Implementation 308 10.5 Balanced Binary Search Trees 309 Right Rotation 310 Left Rotation 310 Rightleft Rotation 311 Leftright Rotation 311 10.6 Implementing Binary Search Trees: AVL Trees 312 Right Rotation in an AVL Tree 313 Left Rotation in an AVL Tree 315 Rightleft Rotation in an AVL Tree 315 Leftright Rotation in an AVL Tree 315 10.7 Implementing Binary Search Trees: Red/Black Trees 315 Insertion into a Red/Black Tree 316 Element Removal from a Red/Black Tree 319 10.8 Implementing Binary Search Trees: The Java Collections API 321 10.9 A Philosophical Quandary 325 Chapter 11 Priority Queues and Heaps 333 11.1 A Heap 334 The addElement Operation 334 The removeMin Operation 337 The findMin Operation 338 11.2 Using Heaps: Priority Queues 339
  • 26.
    CONTENTS xxi 11.3 ImplementingHeaps: With Links 343 The addElement Operation 343 The removeMin Operation 346 The findMin Operation 349 11.4 Implementing Heaps: With Arrays 350 The addElement Operation 350 The removeMin Operation 352 The findMin Operation 353 11.5 Using Heaps: Heap Sort 354 Chapter 12 Multi-way Search Trees 361 12.1 Combining Tree Concepts 362 12.2 2-3 Trees 362 Inserting Elements into a 2-3 Tree 362 Removing Elements from a 2-3 Tree 365 12.3 2-4 Trees 369 12.4 B-Trees 369 B*-trees 371 B+-trees 372 Analysis of B-trees 372 12.5 Implementation Strategies for B-Trees 373 Chapter 13 Graphs 377 13.1 Undirected Graphs 378 13.2 Directed Graphs 380 13.3 Networks 381 13.4 Common Graph Algorithms 382 Traversals 383 Testing for Connectivity 387 Minimum Spanning Trees 388 Determining the Shortest Path 391 13.5 Strategies for Implementing Graphs 392 Adjacency Lists 392 Adjacency Matrices 393
  • 27.
    xxii CONTENTS 13.6 ImplementingUndirected Graphs with an Adjacency Matrix 395 The addEdge Method 399 The addVertex Method 400 The extendCapacity Method 401 Other Methods 401 Chapter 14 Hashing 407 14.1 Hashing 408 14.2 Hashing Functions 410 The Division Method 410 The Folding Method 411 The Mid-Square Method 411 The Radix Transformation Method 412 The Digit Analysis Method 412 The Length-Dependent Method 412 Hashing Functions in the Java Language 413 14.3 Resolving Collisions 413 Chaining 413 Open Addressing 416 14.4 Deleting Elements from a Hash Table 419 Deleting from a Chained Implementation 420 Deleting from an Open Addressing Implementation 420 14.5 Hash Tables in the Java Collections API 421 The Hashtable Class 422 The HashSet Class 424 The HashMap Class 424 The IdentityHashMap Class 424 The WeakHashMap Class 425 LinkedHashSet and LinkedHashMap 428 Chapter 15 Sets and Maps 435 15.1 A Set Collection 436 15.2 Using a Set: Bingo 439
  • 28.
    CONTENTS xxiii 15.3 Implementinga Set: With Arrays 443 The add Operation 445 The addAll Operation 447 The removeRandom Operation 448 The remove Operation 449 The union Operation 450 The contains Operation 451 The equals Operation 452 Other Operations 453 UML Description 453 15.4 Implementing a Set: With Links 455 The add Operation 456 The removeRandom Operation 457 The remove Operation 458 Other Operations 459 15.5 Maps and the Java Collections API 459 Appendix A UML 467 The Unified Modeling Language (UML) 468 UML Class Diagrams 468 UML Relationships 469 Appendix B Object-Oriented Design 475 B.1 Overview of Object-Orientation 476 B.2 Using Objects 476 Abstraction 477 Creating Objects 478 B.3 Class Libraries and Packages 480 The import Declaration 480 B.4 State and Behavior 481 B.5 Classes 482 Instance Data 485 B.6 Encapsulation 486 Visibility Modifiers 486 Local Data 488
  • 29.
    xxiv CONTENTS B.7 Constructors488 B.8 Method Overloading 489 B.9 References Revisited 490 The null Reference 490 The this Reference 491 Aliases 493 Garbage Collection 494 Passing Objects as Parameters 495 B.10 The static Modifier 495 Static Variables 495 Static Methods 496 B.11 Wrapper Classes 497 B.12 Interfaces 498 The Comparable Interface 499 The Iterator Interface 500 B.13 Inheritance 500 Derived Classes 501 The protected Modifier 503 The super Reference 503 Overriding Methods 504 B.14 Class Hierarchies 504 The Object Class 505 Abstract Classes 506 Interface Hierarchies 508 B.15 Polymorphism 508 References and Class Hierarchies 509 Polymorphism via Inheritance 510 Polymorphism via Interfaces 512 B.16 Generic Types 514 B.17 Exceptions 515 Exception Messages 515 The try Statement 516 Exception Propagation 517 The Exception Class Hierarchy 517 Index 527
  • 30.
    1 C H AP T E R O B J E C T I V E S ■ Identify various aspects of software quality ■ Motivate the need for data structures based upon quality issues ■ Introduce the basic concept of a data structure ■ Introduce several elementary data structures Introduction Our exploration of data structures begins with an overview of the underlying issues surrounding the quality of software systems. It is important for us to understand that it is necessary for systems to work as specified, but simply working is not sufficient. We must also develop quality sys- tems. This chapter discusses a variety of issues related to software quality and data structures, and it establishes some terminology that is crucial to our exploration of data struc- tures and software design. 1 1
  • 31.
    2 CHAPTER 1Introduction 1.1 Software Quality Imagine a scenario where you are approaching a bridge that has recently been built over a large river. As you approach, you see a sign informing you that the bridge was designed and built by local construction workers and that engineers were not involved in the proj- ect. Would you continue across the bridge? Would it make a difference if the sign in- formed you that the bridge was designed by engineers and built by construction workers? The word “engineer” in this context refers to an individual who has been educated in the history, theory, method, and practice of the engineering discipline. This defini- tion includes fields of study such as electrical engineering, mechanical engineering, and chemical engineering. Software engineering is the study of the techniques and theory that underlie the development of high-quality software. When the term “software engineering” was first coined in the 1970s, it was an as- piration—a goal set out by leaders in the industry who realized that much of the soft- ware being created was of poor quality. They wanted developers to move away from the simplistic idea of writing programs and toward the disciplined idea of engineering software. To engineer software we must first realize that this term is more than just a title and that it, in fact, represents a completely different attitude. Many arguments have been started over the question of whether software engineer- ing has reached the state of a true engineering discipline. We will leave that argument for software engineering courses. For our purposes, it is sufficient to understand that as software developers we share a common history, we are constrained by common the- ory, and we must understand current methods and practices in order to work together. Ultimately, we want to satisfy the client, the person or organization who pays for the software to be developed, as well as the final users of the system, which may include the client, depending on the situation. The goals of software engineering are much the same as those for other engi- neering disciplines: ■ Solve the right problem ■ Deliver a solution on time and within budget ■ Deliver a high-quality solution ■ Accomplish these things in an ethical manner (see www.acm.org/about/ code-of-ethics) Sir Isaac Newton is credited with the quote “If I have seen further it is by stand- ing on the shoulders of giants.” As modern software developers, we stand upon the shoulders of the giants that founded and developed our field. To truly stand upon their shoulders, we must understand, among other things, the fundamentals of quality software systems and the organization, storage, and retrieval of data. These are the building blocks upon which modern software development is built.
  • 32.
    1.1 Software Quality3 Quality Characteristic Description The degree to which software adheres to its specific requirements. The frequency and criticality of software failure. The degree to which erroneous situations are handled gracefully. The ease with which users can learn and execute tasks within the software. The ease with which changes can be made to the software. The ease with which software components can be reused in the development of other software systems. The ease with which software components can be used in multiple computer environments. The degree to which the software fulfills its purpose without wasting resources. Correctness Reliability Robustness Usability Maintainability Reusability Portability Efficiency FIGURE 1.1 Aspects of software quality To maximize the quality of our software, we must first realize that quality means different things to different people. And there are a variety of quality char- acteristics to consider. Figure 1.1 lists several aspects of high-quality software. Correctness The concept of correctness goes back to our original goal to develop the appropriate solution. At each step along the way of developing a program, we want to make sure that we are addressing the problem as defined by the requirements specification and that we are providing an accurate solution to that problem. Almost all other aspects of quality are meaningless if the software doesn’t solve the right problem. Reliability If you have ever attempted to access your bank account electronically and been unable to do so, or if you have ever lost all of your work be- cause of a failure of the software or hardware you were using, you are already familiar with the concept of reliability. A software failure can be defined as any unacceptable behavior that occurs within permissi- ble operating conditions. We can compute measures of reliability, such as the mean time between failures or the number of operations or tasks between failures. KEY CONCEPT Reliable software seldom fails and, when it does, it minimizes the effects of that failure.
  • 33.
    4 CHAPTER 1Introduction In some situations, reliability is an issue of life and death. In the early 1980s, a piece of medical equipment called the Therac-25 was designed to deliver a dose of radiation according to the settings made by a technician on a special key- board. An error existed in the software that controlled the device and when the technician made a very specific adjustment to the values on the keyboard, the in- ternal settings of the device were changed drastically and a lethal dose of radia- tion was issued. The error occurred so infrequently that several people died be- fore the source of the problem was determined. In other cases, reliability repercussions are financial. On a particular day in November, 1998, the entire AT&T network infrastructure in the eastern United States failed, causing major interruption in communications capabilities. The problem was eventually traced back to a specific software error. That one failure cost millions of dollars in lost revenue to the companies affected. Robustness Reliability is related to how robust a system is. A robust system handles problems gracefully. For example, if a particular input field is designed to handle numeric data, what happens when alphabetic information is entered? The program could be allowed to terminate abnormally because of the result- ing error. However, a more robust solution would be to design the system to acknowledge and handle the situation transparently or with an appropriate error message. Developing a thoroughly robust system may or may not be worth the develop- ment cost. In some cases, it may be perfectly acceptable for a program to abnor- mally terminate if very unusual conditions occur. On the other hand, if adding such protections is not excessively costly, it is simply considered to be good de- velopment practice. Furthermore, well-defined system requirements should care- fully spell out the situations in which robust error handling is required. Usability To be effective, a software system must be truly usable. If a system is too dif- ficult to use, it doesn’t matter if it provides wonderful functionality. Within the discipline of computer science there is a field of study called Human- Computer Interaction (HCI) that focuses on the analysis and design of user interfaces of software systems. The interaction between the user and system must be well designed, including such things as help options, meaningful messages, consistent layout, appropriate use of color, error prevention, and error recovery.
  • 34.
    1.1 Software Quality5 Maintainability Software developers must maintain their software. That is, they must make changes to software in order to fix errors, to enhance the functionality of the system, or simply to keep up with evolving requirements. A useful software system may need to be maintained for many years after its original development. The software engi- neers who perform maintenance tasks are often not the same ones as those who originally developed the software. Thus, it is important that a software system be well structured, well written, and well documented in order to maxi- mize its maintainability. Large software systems are rarely written by a single individual or even a small group of developers. Instead, large teams, often working from widely distributed locations, work together to develop systems. For this reason, communication among developers is critical. Therefore, creating maintainable software is benefi- cial for the long term as well as for the initial development effort. Reusability Suppose that you are a contractor involved in the construction of an office building. It is possible that you might design and build each door in the building from scratch. This would require a great deal of engineering and construction effort, not to mention money. Another option is to use pre-engineered, prefabricated doors for the doorways in the building. This approach represents a great savings of time and money because you can rely on a proven design that has been used many times be- fore. You can be confident that it has been thoroughly tested and that you know its capabilities. However, this does not exclude the possibility that a few doors in the building will be custom engineered and custom built to fit a specific need. When developing a software system, it often makes sense to use pre-existing software components if they fit the needs of the developer and the client. Why reinvent the wheel? Pre-existing components can range in scope from the entire system, to entire subsystems, to individual classes and methods. They may come from part of another system developed earlier or from libraries of components that are created to support the development of future systems. Some pre-existing com- ponents are referred to as Commercial Off-The-Shelf (COTS) products. Pre-exist- ing components are often reliable because they have been tested in other systems. Using pre-existing components can reduce the development effort. However, reuse comes at a price. The developer must take the time to investigate potential components to find the right one. Often the component must be modified or ex- tended to fit the criteria of the new system. Thus, it is helpful if the component is truly reusable. That is, software should be written and documented so that it can KEY CONCEPT Software systems must be carefully designed, written, and documented to support the work of developers, maintainers, and users.
  • 35.
    6 CHAPTER 1Introduction be easily incorporated into new systems and easily modified or extended to ac- commodate new requirements. Portability Software that is easily portable, can be moved from one computing environment to another with little or no effort. Software developed using a particular operat- ing system and underlying central processing unit (CPU) may not run well or at all in another environment. One obvious problem is a program that has been compiled into a particular CPU’s machine language. Because each type of CPU has its own machine language, porting it to another machine would require an- other, translated version. Differences in the various translations may cause the “same” program on two types of machines to behave differently. Using the Java programming language addresses this issue because Java source- code is compiled into bytecode, which is a low-level language that is not the ma- chine language for any particular CPU. Bytecode runs on a Java Virtual Machine (JVM), which is software that interprets the bytecode and executes it. Therefore, at least theoretically, any system that has a JVM can execute any Java program. Efficiency The last software quality characteristic listed in Figure 1.1 is efficiency. Software systems should make efficient use of the resources allocated to them. Two key re- sources are CPU time and memory. User demands on computers and their software have risen steadily ever since computers were first created. Software must always make the best use of its re- sources in order to meet those demands. The efficiency of individ- ual algorithms is an important part of this issue and is discussed in more detail in the next chapter and throughout the book. Quality Issues To a certain extent, quality is in the eye of the beholder. That is, some quality characteristics are more important to certain people than to others. We must con- sider the needs of the various stakeholders, the people affected one way or another by the project. For example, the end user certainly wants to maximize reliability, usability, and efficiency, but doesn’t necessarily care about the software’s maintainability or reusability. The client wants to make sure the user is satisfied, but is also wor- ried about the overall cost. The developers and maintainers want the internal system quality to be high. KEY CONCEPT Software must make efficient use of resources such as CPU time and memory. KEY CONCEPT Quality characteristics must be prioritized, and then maximized to the extent possible.
  • 36.
    1.2 Data Structures7 Note also that some quality characteristics are in competition with each other. For example, to make a program more efficient, we may choose to use a complex algo- rithm that is difficult to understand and therefore hard to maintain. These types of trade-offs require us to carefully prioritize the issues related to a particular project and, within those boundaries, maximize all quality characteristics as much as possi- ble. If we decide that we must use the more complex algorithm for efficiency, we can also document the code especially well to assist with future maintenance tasks. Although all of these quality characteristics are important, for our exploration of data structures in this book, we will focus upon reliability, robustness, reusabil- ity and efficiency. In the creation of data structures, we are not creating applica- tions or end-user systems but rather reusable components that may be used in a variety of systems. Thus, usability is not an issue since there will not be a user in- terface component of our data structures. By implementing in Java and adhering to Javadoc standards, we also address the issues of portability and maintainability. 1.2 Data Structures Why spend so much time talking about software engineering and software quality in a text that focuses on data structures and their algorithms? Well, as you begin to develop more complex programs, it’s important to develop a more mature out- look on the process. As we discussed at the beginning of this chapter, the goal should be to engineer software, not just write code. The data structures we exam- ine in this book lay the foundation for complex software that must be carefully designed. Let’s consider an example that will illustrate the need for and the vari- ous approaches to data structures. A Physical Example Imagine that you must design the process for how to handle shipping containers being unloaded from cargo ships at a dock. In a perfect scenario, the trains and trucks that will haul these containers to their destinations will be waiting as the ship is unloaded and thus there would not be a need to store the containers at all. However, such timing is unlikely, and would not necessarily provide the most effi- cient result for the trucks and the trains since they would have to sit and wait while each ship was unloaded. Instead, as each shipping container is unloaded from a ship, it is moved to a storage location where it will be held until it is loaded on either a truck or a train. Our goal should be to make both the unload- ing of containers and the retrieval of containers for transportation as efficient as possible. This will mean minimizing the amount of searching required in either process and minimizing the number of times a container is moved.
  • 37.
    8 CHAPTER 1Introduction Before we go any further, let’s examine the initial assumptions underlying this problem. First, our shipping containers are generic. By that we mean that they are all the same shape, same size, and can hold the same volume and types of materials. Second, each shipping container has a unique identification number. This number is the key that determines the final destination of each container and whether it is to be shipped by truck or train. Third, the dock workers handling the containers do not need to know, nor can they know, what is inside of each container. Given these assumptions as a starting point, how might we design our storage process for these containers? One possibility might be to simply lay out a very large array indexed by the identification number of the container. Keep in mind, however, the identification number is unique, not just for a single ship but for all ships and all shipping containers. That means that we would need to layout an ar- ray of storage at each dock large enough to handle all of the shipping containers in the world. This would also mean that at any given point in time, the vast ma- jority of the units in these physical arrays would be empty. This would appear to be a terrible waste of space and very inefficient. We will explore issues surround- ing the efficiency of algorithms in the next chapter. We could try this same solution but allow the array to collapse and expand like an ArrayList as containers are removed or added. However, given the physical nature of this array, such a solution may involve having to move containers multi- ple times as other containers with lower ID numbers are added or removed. Again, such a solution would be very inefficient. What if we could estimate the maximum number of shipping containers that we would be storing on our dock at any given point in time? This would create the possibility of creating an array of that maximum size and then simply placing each container into the next available position in the array as it is unloaded from the ship. This would be relatively efficient for unloading purposes since the dock workers would simply keep track of which locations in the array were empty and place each new container in an empty location. However, using this approach, what would happen when a truck driver arrived looking for a particular con- tainer? Since the array is not ordered by container ID, the driver would have to search for the container in the array. In the worst case scenario, the container they are seeking would be the last one in the array causing them to search the entire ar- ray. Of course, the average case would be that each driver would have to search half of the array. Again, this seems less efficient than it could be. Before we try a new design, let’s reconsider what we know about each container. Of course, we have the container ID. But from that, we also have the destination of each container. What if instead of an abitrary ordering of containers in a one- dimensional array, we create a two-dimensional array where the first dimension is the destination? Thus we can implement our previous solution as the second dimen- sion within each destination. Unloading a container is still quite simple. The dock
  • 38.
    1.2 Data Structures9 workers would simply take the container to the array for its destination and place it in the first available empty slot. Then our truck drivers would not have to search the entire dock for their shipping container, only that portion, the array within the array, that is bound for their destination. This solution, which is beginning to be- have like a data structure called a hash table (discussed in Chapter 13), is an im- provement but still requires searching at least a portion of the storage. The first part of this solution, organizing the first dimension by destination, seems like a good idea. However, using a simple unordered array for the second dimension still does not accomplish our goal. There is one additional piece of in- formation that we have for each container that we have yet to examine—the order that it has been unloaded from the ship. Let’s consider an example for a moment of the components of an oil rig being shipped in multiple containers. Does the order of those containers matter? Yes. The crew constructing the oil rig must receive and install the foundation and base components before being able to construct the top of the rig. Now the order the containers are removed from the ship and the order they are placed in storage is important. To this point, we have been considering only the problem of unloading, storing, and shipping storage containers. Now we begin to see that this problem exists within a larger context including how the ship was loaded at its point of origin. Three possibilities exist for how the ship was loaded: containers that are order dependent were loaded in the order they are needed, containers that are order dependent were loaded in the reverse order they are needed, or containers that are order dependent were loaded without regard to order but with order included as part of the information associ- ated with the container ID. Let’s consider each of these cases separately. Keep in mind that the process of unloading the ship will reverse the order of the loading process onto the ship. This behavior is very much like that of a stack, data structure, which we will discuss further in Chapters 3 and 4. If the ship was loaded in the order the components are needed, then the unloading process will reverse the order. Thus our storage and retrieval process must reverse the order again in order to get the containers back into the correct order. This would be accomplished by taking the containers to the array for their destination and storing them in the order they were unloaded. Then the trucker retrieving these containers would simply start with the last one stored. Finally, with this solution we have a storage and retrieval process that involves no searching at all and no extra handling of containers. What if the containers were loaded onto the ship in the reverse or- der they are needed? In that case, unloading the ship will bring the containers off in the order they will be needed and our storage and retrieval process must preserve that order. This would be accom- plished by taking the containers to the array for their destination, storing them in the order they were unloaded, and then having the truckers start with the first container stored rather than the last. Again, this solution does not KEY CONCEPT A stack can be used to reverse the order of a set of data.
  • 39.
    10 CHAPTER 1Introduction involve any searching or extra handling of containers. This behavior is that of a queue data structure, which will be discussed in detail in Chapter 5. Both of our previous solutions, while very efficient, have been de- pendent upon the order that the containers were placed aboard ship. What do we do if the containers were not placed aboard in any par- ticular order? In that case, we will need to order the destination array by the priority order of the containers. Rather than trying to exhaust this example, let’s just say that there are several data structures that might accom- plish this purpose including ordered lists (Chapter 6), priority queues and heaps (Chapter 11), and hash tables (Chapter 13). We also have the additional issue of how best to organize the file that relates container IDs to the other information about each container. Solutions to this problem might include binary search trees (Chapter 10) and multi-way search trees (Chapter 12). Containers as Objects Our shipping container example illustrates another issue surrounding data struc- tures beyond our discussion of how to store the containers. It also illustrates the issue of what the containers store. Early in our discussion, we made the assump- tion that all shipping containers have the same shape and same size, and can hold the same volume and type of material. While the first two assumptions must re- main true in order for containers to be stored and shipped interchangeably, the latter assumptions may not be true. For example, consider the shipment of materials that must remain refrigerated. It may be useful to develop refrigerated shipping containers for this purpose. Similarly some products require very strict humidity control and might require a container with additional environmental controls. Others might be designed for hazardous material and may be lined and/or double walled for protection. Once we develop multiple types of containers, then our containers are no longer generic. We can then think of shipping containers as a hierarchy much like a class hierarchy in object-oriented programming. Thus assigning material to a shipping container becomes analogous to assigning an object to a reference. With both shipping containers and objects, not all assignments are valid. We will discuss is- sues of type compatibility, inheritance, polymorphism, and creating generic data structures in Chapter 3. KEY CONCEPT A queue preserves the order of its data.
  • 40.
    Summary of KeyConcepts 11 Summary of Key Concepts ■ Reliable software seldom fails and, when it does, it minimizes the effects of that failure. ■ Software systems must be carefully designed, written, and documented to support the work of developers, maintainers, and users. ■ Software must make efficient use of resources such as CPU time and memory. ■ Quality characteristics must be prioritized, and then maximized to the extent possible. ■ A stack can be used to reverse the order of a set of data. ■ A queue preserves the order of its data. Self-Review Questions SR 1.1 What is the difference between software engineering and pro- gramming? SR 1.2 Name several software quality characteristics. SR 1.3 What is the relationship between reliability and robustness? SR 1.4 Describe the benefits of developing software that is maintainable. SR 1.5 How does the Java programming language address the quality characteristic of portability? SR 1.6 What is the principle difference in behavior between a stack and a queue? SR 1.7 List two common data structures that might be used to order a set of data. Exercises EX 1.1 Compare and contrast software engineering with other engineer- ing disciplines. EX 1.2 Give a specific example that illustrates each of the software qual- ity characteristics listed in Figure 1.1. EX 1.3 Provide an example, and describe the implications, of a trade-off that might be necessary between quality characteristics in the de- velopment of a software system.
  • 41.
    12 CHAPTER 1Introduction Answers to Self-Review Questions SRA 1.1 Software engineering is concerned with the larger goals of system design and development, not just the writing of code. Programmers mature into software engineers as they begin to understand the issues related to the development of high-quality software and adopt the appropriate practices. SRA 1.2 Software quality characteristics include: correctness, reliability, robustness, usability, maintainability, reusability, portability, and efficiency. SRA 1.3 Reliability is concerned with how often and under what circum- stances a software system fails, and robustness is concerned with what happens when a software system fails. SRA 1.4 Software that is well structured, well designed, and well docu- mented is much easier to maintain. These same characteristics also provide benefit for distributed development. SRA 1.5 The Java programming language addresses this issue by compiling into bytecode, which is a low-level language that is not the ma- chine language for any particular CPU. Bytecode runs on a Java Virtual Machine (JVM), which is software that interprets the bytecode and executes it. Therefore, at least theoretically, any sys- tem that has a JVM can execute any Java program. SRA 1.6 A stack reverses order whereas a queue preserves order. SRA 1.7 Common data structures that can be used to order a set of data include ordered lists, heaps, and hash tables.
  • 42.
    13 C H AP T E R O B J E C T I V E S ■ Discuss the goals of software development with respect to efficiency ■ Introduce the concept of algorithm analysis ■ Explore the concept of asymptotic complexity ■ Compare various growth functions Analysis of Algorithms It is important that we understand the concepts surround- ing the efficiency of algorithms before we begin building data structures. A data structure built correctly and with an eye toward efficient use of both the CPU and memory is one that can be reused effectively in many different applications. However, a data structure that is not built efficiently is simi- lar to using a damaged original as the master from which to make copies. 2 2
  • 43.
    14 CHAPTER 2Analysis of Algorithms 2.1 Algorithm Efficiency One of the quality characteristics discussed in section 1.1 is the efficient use of re- sources. One of the most important resources is CPU time. The efficiency of an al- gorithm we use to accomplish a particular task is a major factor that determines how fast a program executes. Although the techniques that we will discuss here may also be used to analyze an algorithm relative to the amount of memory it uses, we will focus our discussion on the efficient use of processing time. The analysis of algorithms is a fundamental computer science topic and involves a variety of techniques and concepts. It is a primary theme that we return to throughout this book. This chapter introduces the issues related to algorithm analysis and lays the groundwork for using analysis techniques. Let’s start with an everyday example: washing dishes by hand. If we assume that washing a dish takes 30 seconds and drying a dish takes an additional 30 sec- onds, then we can see quite easily that it would take n minutes to wash and dry n dishes. This computation could be expressed as follows: Time (n dishes) = n * (30 seconds wash time + 30 seconds dry time) = 60n seconds or, written more formally: f(x) = 30x + 30x f(x) = 60x On the other hand, suppose we were careless while washing the dishes and splashed too much water around. Suppose each time we washed a dish, we had to dry not only that dish but also all of the dishes we had washed before that one. It would still take 30 seconds to wash each dish, but now it would take 30 seconds to dry the last dish (once), 2 * 30 or 60 seconds to dry the second-to-last dish (twice), 3 * 30 or 90 seconds to dry the third-to-last dish (three times), and so on. This computation could be expressed as follows: Using the formula for an arithmetic series then the function becomes Time (n dishes) = 30n + 30n(n + 1)/2 = 15n2 + 45n seconds If there were 30 dishes to wash, the first approach would take 30 minutes, whereas the second (careless) approach would take 247.5 minutes. The more dishes g n 1 i = n(n + 1)/2 Time (n dishes) = n * (30 seconds wash time) + a n i=1 (i * 30) KEY CONCEPT Algorithm analysis is a fundamental computer science topic.
  • 44.
    2.2 Growth Functionsand Big-OH Notation 15 we wash the worse that discrepancy becomes. For example, if there were 300 dishes to wash, the first approach would take 300 minutes or 5 hours, whereas the second approach would take 908,315 minutes or roughly 15,000 hours! 2.2 Growth Functions and Big-OH Notation For every algorithm we want to analyze, we need to define the size of the problem. For our dishwashing example, the size of the problem is the number of dishes to be washed and dried. We also must determine the value that represents efficient use of time or space. For time considerations, we often pick an appropriate processing step that we’d like to minimize, such as our goal to minimize the number of times a dish has to be washed and dried. The overall amount of time spent on the task is directly related to how many times we have to perform that task. The algorithm’s efficiency can be defined in terms of the problem size and the processing step. Consider an algorithm that sorts a list of numbers into increasing order. One natural way to express the size of the problem would be the number of values to be sorted. The processing step we are trying to optimize could be expressed as the number of comparisons we have to make for the algorithm to put the values in order. The more comparisons we make, the more CPU time is used. A growth function shows the relationship between the size of the problem (n) and the value we hope to optimize. This function represents the time complexity or space complexity of the algorithm. The growth function for our second dishwashing algorithm is t(n) = 15n2 + 45n However, it is not typically necessary to know the exact growth function for an algorithm. Instead, we are mainly interested in the asymptotic complexity of an algorithm. That is, we want to focus on the general nature of the function as n in- creases. This characteristic is based on the dominant term of the expression—the term that increases most quickly as n increases. As n gets very large, the value of the dishwashing growth function is dominated by the n2 term because the n2 term grows much faster than the n term. The constants, in this case 15 and 45, and the secondary term, in this case 45n, quickly become irrelevant as n increases. That is to say, the value of n2 dominates the growth in the value of the expression. The table in Figure 2.1 shows how the two terms and the value of the expres- sion grow. As you can see from the table, as n gets larger, the 15n2 term domi- nates the value of the expression. It is important to note that the 45n term is larger for very small values of n. Saying that a term is the dominant term as n gets large does not mean that it is larger than the other terms for all values of n. KEY CONCEPT A growth function shows time or space utilization relative to the problem size.
  • 45.
    16 CHAPTER 2Analysis of Algorithms The asymptotic complexity is called the order of the algorithm. Thus, our sec- ond dishwashing algorithm is said to have order n2 time complexity, written O(n2). Our first, more efficient dishwashing example, with growth function t(n) = 60(n) would have order n, written O(n). Thus the reason for the difference be- tween our O(n) original algorithm and our O(n2) sloppy algorithm is the fact each dish will have to be dried multiple times. This notation is referred to as O() or Big-Oh notation. A growth function that executes in constant time regardless of the size of the problem is said to have O(1). In general, we are only concerned with executable statements in a program or algorithm in determining its growth function and efficiency. Keep in mind, however, that some declarations may include initializations and some of these may be complex enough to factor into the efficiency of an algorithm. As an example, assignment statements and if statements that are only executed once regardless of the size of the problem are O(1). Therefore, it does not matter how many of those you string together; it is still O(1). Loops and method calls may result in higher order growth functions because they may result in a statement or series of statements being executed more than once based on the size of the problem. We will discuss these separately in later sections of this chapter. Figure 2.2 shows several growth functions and their asymptotic complexity. More formally, saying that the growth function t(n) = 15n2 + 45n is O(n2) means that there exists a constant m and some value of n (n0), such that t(n) … m*n2 for all n 7 n0. Another way of stating this is that the order of an algorithm provides an upper bound to its growth func- tion. It is also important to note that there are other related notations such as omega (Ω) which refers to a function that provides a lower Number of dishes (n) 1 2 5 10 100 1,000 10,000 100,000 1,000,000 10,000,000 15 60 375 1,500 150,000 15,000,000 1,500,000,000 150,000,000,000 15,000,000,000,000 1,500,000,000,000,000 15n2 45 90 225 450 4,500 45,000 450,000 4,500,000 45,000,000 450,000,000 45n 60 150 600 1,950 154,500 15,045,000 1,500,450,000 150,004,500,000 15,000,045,000,000 1,500,000,450,000,000 15n2 ⴙ 45n FIGURE 2.1 Comparison of terms in growth function KEY CONCEPT The order of an algorithm provides an upper bound to the algorithm’s growth function. KEY CONCEPT The order of an algorithm is found by eliminating constants and all but the dominant term in the algorithm’s growth function.
  • 46.
    2.3 Comparing GrowthFunctions 17 bound and theta (Θ) which refers to a function that provides both an upper and lower bound. We will focus our discussion on order. Because the order of the function is the key factor, the other terms and constants are often not even mentioned. All algorithms within a given order are considered to be generally equivalent in terms of efficiency. For example, while two algorithms to accomplish the same task may have different growth functions, if they are both O(n2) then they are considered to be roughly equivalent with respect to efficiency. 2.3 Comparing Growth Functions One might assume that, with the advances in the speed of processors and the avail- ability of large amounts of inexpensive memory, algorithm analysis would no longer be necessary. However, nothing could be farther from the truth. Processor speed and memory cannot make up for the differences in efficiency of algorithms. Keep in mind that in our previous discussion we have been eliminating constants as irrelevant when discussing the order of an algorithm. Increasing processor speed simply adds a constant to the growth function. When possible, finding a more effi- cient algorithm is a better solution than finding a faster processor. Another way of looking at the effect of algorithm complexity was proposed by Aho, Hopcroft, and Ullman (1974). If a system can currently handle a problem of size n in a given time period, what happens to the allowable size of the problem if we increase the speed of the processor tenfold? As shown in Figure 2.3, the linear case is relatively simple. Algorithm A, with a linear time complexity of n, is indeed improved by a factor of 10, meaning that this algorithm can process 10 times the data in the same amount of time given a tenfold speed up of the processor. However, algorithm B, with a time complexity of n2, is only improved by a factor of 3.16. Why do we not get the full tenfold increase in problem size? Because the complexity of algorithm B is n2 our effective speedup is only the square root of 10 or 3.16. Growth Function t(n) = 17 t(n) = 3log n t(n) = 20n – 4 t(n) = 12n log n + 100n t(n) = 3n2 + 5n – 2 t(n) = 8n3 + 3n2 t(n) = 2n + 18n2 + 3n O(1) O(log n) O(n) O(n log n) O(n2) O(n3) O(2n) Order constant logarithmic linear n log n quadratic cubic exponential Label FIGURE 2.2 Some growth functions and their asymptotic complexity
  • 47.
    18 CHAPTER 2Analysis of Algorithms Similarly, algorithm C, with complexity n3, is only improved by a factor of 2.15 or the cube root of 10. For algorithms with exponential complexity like algorithm D, in which the size variable is in the exponent of the complexity term, the situation is far worse. In this case the speed up is log2n or in this case, 3.3. Note this is not a factor of 3, but the original problem size plus 3. In the grand scheme of things, if an algorithm is inefficient, speeding up the processor will not help. Figure 2.4 illustrates various growth functions graphically for relatively small values of n. Note that when n is small, there is little difference between the algo- Algorithm A B C D Time Complexity n n2 n3 2n Max Problem Size Before Speedup s1 s2 s3 s4 Max Problem Size After Speedup 10s1 3.16s2 2.15s3 s4 + 3.3 FIGURE 2.3 Increase in problem size with a tenfold increase in processor speed 500 200 100 0 Time 1 5 10 15 25 20 300 400 Input Size (N) log n n n log n n2 n3 2n FIGURE 2.4 Comparison of typical growth functions for small values of n KEY CONCEPT If the algorithm is inefficient, a faster processor will not help in the long run.
  • 48.
    2.4 Determining TimeComplexity 19 rithms. That is, if you can guarantee a very small problem size (5 or less), it doesn’t really matter which algorithm is used. However, notice that in Figure 2.5, as n gets very large, the differences between the growth functions become obvious. 2.4 Determining Time Complexity Analyzing Loop Execution To determine the order of an algorithm, we have to determine how often a particular statement or set of statements gets executed. Therefore, we often have to determine how many times the body of a loop is executed. To analyze loop execution, first determine the order of the body of the loop, and then multiply that by the number of times the loop will execute relative to n. Keep in mind that n repre- sents the problem size. 200,000 100,000 50,000 0 Time 150,000 100 1 200 300 500 400 log n n n log n n2 n3 2n Input Size (N) FIGURE 2.5 Comparison of typical growth functions for large values of n KEY CONCEPT Analyzing algorithm complexity of- ten requires analyzing the execution of loops.
  • 49.
    20 CHAPTER 2Analysis of Algorithms Assuming that the body of a loop is O(1), then a loop such as this: for (int count = 0; count < n; count++) { /* some sequence of O(1) steps */ } would have O(n) time complexity. This is due to the fact that the body of the loop has O(1) complexity but is executed n times by the loop structure. In general, if a loop structure steps through n items in a linear fashion and the body of the loop is O(1), then the loop is O(n). Even in a case where the loop is designed to skip some number of elements, as long as the progression of elements to skip is linear, the loop is still O(n). For example, if the preceding loop skipped every other num- ber (e.g. count += 2), the growth function of the loop would be n/2, but since con- stants don’t affect the asymptotic complexity, the order is still O(n). Let’s look at another example. If the progression of the loop is logarithmic such as the following: count = 1 while (count < n) { count *= 2; /* some sequence of O(1) steps */ } then the loop is said to be O(log n). Note that when we use a loga- rithm in an algorithm complexity, we almost always mean log base 2. This can be explicitly written as O(log2n). Since each time through the loop the value of count is multiplied by 2, the number of times the loop is executed is log2n. Nested Loops A slightly more interesting scenario arises when loops are nested. In this case, we must multiply the complexity of the outer loop by the complexity of the inner loop to find the resulting complexity. For example, the following nested loops: for (int count = 0; count < n; count++) { for (int count2 = 0; count2 < n; count2++) { /* some sequence of O(1) steps */ } } KEY CONCEPT The time complexity of a loop is found by multiplying the complexity of the body of the loop by how many times the loop will execute.
  • 50.
    2.4 Determining TimeComplexity 21 would have complexity O(n2). The body of the inner loop is O(1) and the inner loop will execute n times. This means the inner loop is O(n). Multiplying this result by the number of times the outer loop will execute (n) results in O(n2). What is the complexity of the following nested loop? for (int count = 0; count < n; count++) { for (int count2 = count; count2 < n; count2++) { /* some sequence of O(1) steps */ } } In this case, the inner loop index is initialized to the current value of the index for the outer loop. The outer loop executes n times. The inner loop executes n times the first time, n–1 times the second time, etc. However, remember that we are only interested in the dominant term, not in constants or any lesser terms. If the progression is linear, regardless of whether some elements are skipped, the or- der is still O(n). Thus the resulting complexity for this code is O(n2). Method Calls Let’s suppose that we have the following segment of code: for (int count = 0; count < n; count++) { printsum (count); } We know from our previous discussion that we find the order of the loop by multiplying the order of the body of the loop by the number of times the loop will execute. In this case, however, the body of the loop is a method call. Therefore, we must first determine the order of the method before we can determine the or- der of the code segment. Let’s suppose that the purpose of the method is to print the sum of the integers from 1 to n each time it is called. We might be tempted to create a brute force method such as the following: public void printsum(int count) { int sum = 0; for (int I = 1; I < count; I++) sum += I; System.out.println (sum); } KEY CONCEPT The analysis of nested loops must take into account both the inner and outer loops.
  • 51.
    22 CHAPTER 2Analysis of Algorithms What is the time complexity of this printsum method? Keep in mind that only executable statements contribute to the time complexity so in this case, all of the executable statements are O(1) except for the loop. The loop on the other hand is O(n) and thus the method itself is O(n). Now to compute the time com- plexity of the original loop that called the method, we simply multiply the complexity of the method, which is the body of the loop, by the number of times the loop will execute. Our result, then, is O(n2) using this implementa- tion of the printsum method. However, if you recall, we know from our earlier discussion that we do not have to use a loop to calculate the sum of the numbers from 1 to n. In fact, we know that the Now let’s rewrite our printsum method and see what hap- pens to our time complexity: public void printsum(int count) { sum = count*(count+1)/2; System.out.println (sum); } Now the time complexity of the printsum method is made up of an assign- ment statement which is O(1) and a print statement which is also O(1). The result of this change is that the time complexity of the printsum method is now O(1) meaning that the loop that calls this method now goes from being O(n2) to O(n). We know from our our earlier discussion and from Figure 2.5 that this is a very significant improvement. Once again we see that there is a difference between delivering correct results and doing so efficiently. What if the body of a method is made up of multiple method calls and loops? Consider the following code using our printsum method above: g n 1i = n(n + 1)/2. /* this method call is O(1) */ /* this loop is O(n) */ /* this loop is O(n2) */ public void sample(int n) { printsum(n); for (int count = 0; count < n; count++) printsum (count); for (int count = 0; count < n; count++) for (int count2 = 0; count2 < n; count2++) System.out.println (count, count2); } The initial call to the printsum method with the parameter temp is O(1) since the method is O(1). The for loop containing the call to the printsum method with the parameter count is O(n) since the method is O(1) and the loop executes
  • 52.
    2.4 Determining TimeComplexity 23 n times. The nested loops are O(n2) since the inner loop will execute n times each time the outer loop executes and the outer loop will also execute n times. The en- tire method is then O(n2) since only the dominant term matters. More formally, the growth function for the method sample is given by: f(x) = 1 + n + n2 Then given that we eliminate constants and all but the dominant term, the time complexity is O(n2). There is one additional issue to deal with when analyzing the time complexity of method calls and that is recursion, the situation when a method calls itself. We will save that discussion for Chapter 7.
  • 53.
    Summary of KeyConcepts ■ Software must make efficient use of resources such as CPU time and memory. ■ Algorithm analysis is a fundamental computer science topic. ■ A growth function shows time or space utilization relative to the problem size. ■ The order of an algorithm is found by eliminating constants and all but the dominant term in the algorithm’s growth function. ■ The order of an algorithm provides an upper bound to the algorithm’s growth function. ■ If the algorithm is inefficient, a faster processor will not help in the long run. ■ Analyzing algorithm complexity often requires analyzing the execution of loops. ■ The time complexity of a loop is found by multiplying the complexity of the body of the loop by how many times the loop will execute. ■ The analysis of nested loops must take into account both the inner and outer loops. Self-Review Questions SR 2.1 What is the difference between the growth function of an algo- rithm and the order of that algorithm? SR 2.2 Why does speeding up the CPU not necessarily speed up the process by the same amount? SR 2.3 How do we use the growth function of an algorithm to determine its order? SR 2.4 How do we determine the time complexity of a loop? SR 2.5 How do we determine the time complexity of a method call? Exercises EX 2.1 What is the order of the following growth functions? a. 10n2 + 100n + 1000 b. 10n3 – 7 c. 2n + 100n3 d. n2 log n 24 CHAPTER 2 Analysis of Algorithms
  • 54.
    EX 2.2 Arrangethe growth functions of the previous exercise in ascend- ing order of efficiency for n=10 and again for n=1,000,000. EX 2.3 Write the code necessary to find the largest element in an unsorted array of integers. What is the time complexity of this algorithm? EX 2.4 Determine the growth function and order of the following code fragment: for (int count=0; count < n; count++) { for (int count2=0; count2 < n; count2=count2+2) { System.out.println(count, count2); } } EX 2.5 Determine the growth function and order of the following code fragment: for (int count=0; count < n; count++) { for (int count2=0; count2 < n; count2=count2*2) { System.out.println(count, count2); } } EX 2.6 The table in Figure 2.1 shows how the terms of the growth func- tion for our dishwashing example relate to one another as n grows. Write a program that will create such a table for any given growth function. Answers to Self-Review Questions SRA 2.1 The growth function of an algorithm represents the exact rela- tionship between the problem size and the time complexity of the solution. The order of the algorithm is the asymptotic time com- plexity. As the size of the problem grows, the complexity of the algorithm approaches the asymptotic complexity. SRA 2.2 Linear speedup only occurs if the algorithm has constant order, O(1), or linear order, O(n). As the complexity of the algorithm grows, faster processors have significantly less impact. SRA 2.3 The order of an algorithm is found by eliminating constants and all but the dominant term from the algorithm’s growth function. Answers to Self Review Questions 25
  • 55.
    Other documents randomlyhave different content
  • 56.
    The data regardingyour prospective customer is obtainable in many ways. Much of it you may obtain from your house if they have had previous dealings with him. Other salesmen will also add to the data, but one must be on the lookout here and not allow himself to be prejudiced against the customer, or frightened by adverse reports regarding his manner and characteristics coming from other salesmen. Pierce says: "It would seem that the good characteristics of the prospect are desirable to learn. But it is a conviction that by denying to one's self the unfavorable things said about your prospect, you will not accentuate the very qualities you hope to obviate. One attempt at a sale is recalled where the prospect was said to be 'the meanest man on earth.' Almost terrified by the description, the salesman went at the prospect the wrong way; displeased him; lost the sale." Hotel clerks—or better still, hotel proprietors—are often very well informed regarding merchants in their town, and often valuable information may be obtained in this way, although the judgment and experience of the hotel people must be appraised before basing one's own opinion regarding the customer. Other customers may also be diplomatically pressed into service in obtaining information regarding their competitors, although allowance must always be made for the personal bias in such cases. It is a good idea for the salesman to make a record of these advance reports, so as to have them on file where he may refer to them when needed. Some salesmen have a card index devoted to this purpose, which they have found very useful. Another, and a very important point about the Pre-Approach is that of developing the proper Mental Attitude in yourself. You must get yourself right first, before you can get anything else right. Pierce says regarding this: "Someone has said that the greatest bane to selling goods is fear. As a matter of fact, the only thing you are afraid of is that you won't make the sale,—get the check. But, if you waive this point, and say, 'Now, I don't care whether I get this sale or not. I do know this: I am honest, my goods are honest, and if this man does not want them there are plenty of men who do,' you will
  • 57.
    find the fearmelting like the mist before sunshine. Fear cannot live in the presence of your smile, your confidence, your knowledge of the business and your industry." In this connection, re-read what we have said to you regarding the "I" and "Self-Respect" in the chapter entitled "The Mind of the Salesman." This chapter was written to cover just such cases as the one in question. If you can realize the "I" within you, your fear will disappear quickly. Remember, "there's nothing to fear but Fear." Many successful salesmen state that they overcame their early fear and timidity by filling themselves with auto-suggestions that they were calling on the customer for the purpose of doing him a good turn—that it was a good thing for the customer that the salesman was calling on him, although he did not know it—and that he, the salesman must let nothing stand in the way of doing that good turn to the customer, etc. As ridiculous as this may appear to some, it will be found to work well in many cases. And it is based upon truth, too, for if the goods are right, and the prices are likewise, the salesman is doing the customer a good turn. And right here, let us impress upon you the necessity of working yourself up to the point of believing thoroughly in your own proposition. You must get yourself into the state of mind in which, if you were in the customer's place, you would surely want to take advantage of it. You must convert yourself before you can expect to convert the customer. We know an ad. man who tells us that he never feels satisfied with an ad. that he is writing until he can make himself believe that he wants to buy the article himself. And he is right. And the salesman will do well to take a leaf from his book. Enthusiasm and belief are contagious. If you believe thoroughly in a thing, you run a much better chance of making others believe in it also, than if you feel otherwise. You must learn to sell to yourself first, then you may sell to the customer. W.C. Holman, in "Salesmanship," says: "One cannot make others believe what he himself believes, unless he himself is an earnest believer. Dwight L. Moody swayed enormous audiences by the simple
  • 58.
    power of hisown wonderful earnestness. No one could listen to Moody without saying: 'This man believes absolutely every word he is speaking. If he feels what he says so tremendously, there must be something in it.' If every salesman realized how largely the attitude of the 'prospect' depended upon the salesman's own mental attitude, he would be as careful to get into the right frame of mind when he started out to approach a prospect as he would be to carry a sample case. It is a simple matter for him to do this. All that is necessary is for him to 'take account of stock' just before he starts out—to enumerate to himself all the strong, convincing points in his proposition—to consider the good high qualities of the goods he is selling—run over in his mind the splendid characteristics of his house —think of the great number of customers who have bought his product—and of the supremely satisfying reasons why other customers should buy his goods. In other words, before a salesman starts to sell other men, he should sell himself. He should make this sale to himself at the beginning of every day's work." The student should acquaint himself thoroughly with the creative force of Suggestion and Auto-Suggestion in Character Building, and in producing and maintaining the proper Mental Attitude. The volume of this series entitled "Suggestion and Auto-Suggestion" gives both the theory, principles and methods of applying Auto- Suggestion in the directions named. One need no longer be a slave of his Mental Attitude. On the contrary he may create and preserve the Mental Attitude he deems advisable and necessary at any time. Mr. W.C. Holman, one of the best of the inspirational writers on Salesmanship, gives the following interesting instance of the use of Auto-Suggestion by a salesman. He says: "One of the best salesmen the writer ever knew got up what he called his catechism. He used to put himself through it every morning before starting out. Oftentimes he repeated it aloud if he had the opportunity. The questions he would repeat in a quiet tone, but the answers he would pronounce with all the earnestness of which he was capable. His catechism ran somewhat as follows:
  • 59.
    "Am I workingfor a good house? YES! "Has my house the reputation and prestige of being one of the best in its line? YES! "Have we made hundreds of thousands of sales like the sales I am going to make to-day? YES! "Have we an enormous body of satisfied users? YES! "Am I selling the best goods of the kind made anywhere in the world? YES! "Is the price I am asking a fair one? YES! "Do the men I am going to call on need the article I am selling? YES! "Do they realize that now? NO! "Is that the very reason I am going to call on them—because at present they don't want my goods, and haven't yet bought them? YES! "Am I justified in asking a prospect's time and attention to present my proposition? BY ALL THE POWERS, YES! "Am I going to get into the office of every man that I call on, if there is any earthly way to do it? YES! "Am I going to sell every man I call on to-day? YOU BET I AM!" Referring to the above "catechism" of Mr. Holman, we would say that if a man would work himself up to the point of asking and answering these questions in earnest, and would carry the spirit thereof through the day, he would render himself almost invincible. A spirit like that is the spirit of the Light Brigade, of Napoleon, of the Berserker Norseman who made a way for himself. Such a man would make opportunities, instead of begging for them. Such a man would be inspired. This is Auto-Suggestion raised to the Nth Power. Try it— you need it in your business!
  • 60.
    The second phaseof the Pre-Approach is that of obtaining an interview with the prospective customer, generally known as "the prospect." In many instances the salesman is able to secure the interview by simply walking into the presence of the prospect, the latter being in full view in his store or office and no intermediary being present to intercept the approach. In such cases the second phase of the Pre-Approach is passed over, and the actual Approach is entered into at once. But in other cases, particularly in the large office buildings of the principal cities, the prospect is found to be in his private office, and the salesman's advance is halted by a clerk, or even an office boy, and there are certain preliminaries to be gone through with before an interview may be obtained. In many cases, "big" men (or those who wish to be considered "big") surround themselves with so much formality and red-tape that it is quite a feat to run the gauntlet of the guardians of the inner temple, and much tact, diplomacy, presence of mind, and often strategy is required of the Salesman in order that he may "get at his man." Macbain, in his work entitled "Selling," says of this stage: "Between the pre-approach and the actual approach sometimes lies a trying time for the salesman. It is no uncommon thing for a prospective customer to keep a salesman waiting, either outside the office door and out of sight, or inside and in the presence of the prospective buyer. This is known as 'breaking the salesman's nerve.' It is often done with the idea of deliberately making the salesman nervous and consequently unable to make such an approach as otherwise would be possible. Perhaps one of the most common forms of this is seen when the prospective customer appears to be very busily interested in something at his desk and allows the salesman to stand an indefinite length of time and then turns suddenly upon him. This is especially disconcerting to the young man, but the experienced salesman recognizes it as an indication that either the man is very busy and actually hates to take his mind off his work, or that he is afraid of being talked into something that he will later regret. The salesman consequently shapes his introduction accordingly and will in no wise be disconcerted by this
  • 61.
    attempt as itwill enable him to study carefully the outward characteristics of the man whom he is about to approach." In many cases this waiting is forced on the salesman by a prospect who also knows something of the laws of psychology—for such knowledge is not confined to the salesman by any means, the buyer having posted himself in many cases. In the game of checkers or draughts quite an important advantage accrues to the player securing what is technically known as "the move," which, however, is a very different thing from the "first play." There is in the psychology of the sale, or of the interview between two people of equal strength, a something which corresponds very closely with "the move" in checkers. This something gives a decided advantage to the person securing it, and it is worth striving for. This something is subtle and almost indescribable, although apparent to every one who has dealings with his fellow men. It seems to be a matter of mental balance and poise. The salesman, if he be well balanced and poised, is "positive" to the buyer, the latter being in a listening, and therefore passive, attitude. So far the salesman has "the move," which however he may later lose if the prospect plays scientifically. Well, to get back to the "waiting" stage, the prospect by disturbing the salesman's poise, and "breaking his nerve" by keeping him waiting on the anxious bench in a state of suspense, often manages to get "the move" on him, unless he understands the psychology of the process and accordingly avoids it. Suspense is the most nerve- breaking mental state on the psychological list, as all realize who have experienced it. Beware of losing "the move." An important factor in getting past the stockade of the outer office is the consciousness of Self Respect and the realization of the "I" of which we have spoken. This mental attitude impresses itself upon those who guard the outer works, and serves to clear the way. As Pierce says: "Remember, you are asking no favors; that you have nothing to apologize for, and that you have every reason in the world for holding your head high. And it is wonderful what this holding up of the head will do in the way of increasing sales. We have seen salesmen get entrance to the offices of Broadway buyers simply
  • 62.
    through the holdingof the head straight up from the shoulders." But it is the Mental Attitude back of the physical expression that is the spirit of the thing—don't forget this. The Mental Attitude and the physical expression thereof instinctively influence the conduct of other people toward one. We may see the same thing illustrated in the attitude and action of the street boy toward dogs. Let some poor cur trot along with drooping ears, timid expression, meek eyes, and tail between his legs, and the urchin will be apt to kick him or throw a rock at his retreating form. Note the difference when the self-respecting dog, with spirit in him, trots past, looking the boy fearlessly in the eye and showing his sense of self-respect and power to back it up in every movement. That dog is treated accordingly. There are certain people whose manner is such that they do not need to ask respect and consideration—it is given them as a matter of right and privilege. People stand aside to give them room, and move up in street cars that they may have a seat. And it does not necessarily follow that the person to whom this respect is shown is a worthy individual or a person of fine qualities—he may be a confidence man or a swindler. But whatever he is, or may be, he has certain outward mannerisms and characteristics which enable him to "put up a good front" and which carry him through. At the back of it all will be found certain mental states which produce the genuine outward characteristics and manner in the case of genuine instances of persons possessing authority and high position, the confidence man merely presenting a passable counterfeit, being a good actor. It is often necessary for the salesman to send in a card to the inner office. It is well for him to have some cards, well engraved in the most approved manner, bearing simply his name: "Mr. John Jay Jones," with his business appearing thereon. If he is travelling from a large city, and is selling in smaller towns, he may have "New York," "Chicago," "Philadelphia," "Boston," etc., as the case may be in the corner of his card. If the name of his business appears on the card the prospect often goes over the matter of a possible sale, mentally, without the salesman being present to present his case, and then
  • 63.
    may decline togrant an interview. The name, without the business, often arouses interest or curiosity and thus, instead of hindering, really aids in securing the interview. Regarding the discussion of the business with anyone other than the prospect himself, the authorities differ. As a matter of fact it would seem to depend largely upon the particular circumstances of each case, the nature of the articles to be sold, and the character and position of the subordinate in question. One set of authorities hold that it is very poor policy to tell your business to a subordinate, and that it is far better to tell him courteously but firmly that your business is of such a nature that you can discuss it only with the prospect in person. Otherwise, it is held that the subordinate will tell you that the matter in question has already been considered by his principal, and that he is fully informed regarding the proposition, and has given orders that he is not to be disturbed further regarding it. The other set of authorities hold that in many cases the subordinate may be pressed into service, by treating him with great respect, and an apparent belief in his judgment and authority, winning his good-will and getting him interested in your proposition, and endeavoring to have him "speak about it" to his superior during the day. It is claimed that a subsequent call, the day following, will often prove successful, as the subordinate will have paved the way for an interview and have actually done some work for you in the way of influence and selling talk. It is held that some salesmen have made permanent "friends in camp" of these subordinates who have been approached in this way. It would seem, however, as we have said, to depend much upon the particular circumstances of the case. In some cases the subordinate is merely a "hold-off," or "breakwater;" while in others he is a confidential employee whose opinion has weight with the prospect, and whose good-will and aid are well worth securing. In any event, however, it is well to gain the respect and good-will of those in the "outer court," for they can often do much in the way of
  • 64.
    helping or injuringyour chances. We have known cases in which subordinates "queered" a salesman who had offended them; and we have known other cases in which the subordinate being pleased by the salesman "put him next." It is always better to make a friend rather than an enemy—from the office-boy upward—on general principles. Many a fine warrior has been tripped up by a small pebble. Strong men have died from the bite of a mosquito. The following advice from J.F. Gillen, the Chicago manager of the Burroughs Adding Machine Company, is very much to the point. Mr. Gillen, in the magazine "Salesmanship," says: "A salesman who has not proved his mettle—and who, unfortunately, is not sure of himself —is likely to be overcome by a sense of his own insignificance on entering the private domain of the great man, rich man, or influential man, from whom he hopes to get an order. The very hum and rush of business in this boss's office are very awe-inspiring. The fact that there exists an iron-clad rule, designed to protect the boss against intrusion, forbidding the admittance of an uninvited salesman—and the fact that the army of employees are bound by this rule to oppose the entrance of any such visitor—combine to make an untried salesman morally certain of his powerlessness; to make him feel that he has no justifiable reason for presenting himself at all. Indeed he has none, if the awe which he feels for red- tape, rules, dignitaries, has made him lose sight of the attractions of his own proposition; has swallowed up his confidence in what he has to offer and his ability to enthuse the prospect in regard to it. * * * If you believe that your proposition will prove interesting to the prospect and that he will profit by doing business with you, you have a right to feel that the rule barring salesmen from his presence was not intended to bar you. Convince yourself of this and the stern negative of the information clerk will not abash you. You will find yourself endowed with a courage and resourcefulness to cope with a slick secretary who gives glibly evasive replies when you try to find out whether Mr. Prospect is now in his office, whether he cannot see you at once, and what reason exists for supposing you could possibly tell your business to any subordinate in place of him. Once
  • 65.
    you are thusmorally sure of your ground, the hardest part of the battle is won. * * * You can see the prospect and get speech with him, no matter what obstacles intervene, if your nerve holds out and you use your brains." Remember this, always: The Psychology of Salesmanship applies not only to work with the prospect, but also to work with those who bar the way to him. Subordinates have minds, faculties, feelings and strong and weak points of mentality—they have their psychology just as their employer has his. It will pay you to make a careful study of their psychology—it has its rules, laws and principles. This is a point often overlooked by little salesmen, but fully recognized by the "big" ones. The short cut to the mind of many a prospect is directly through the mind of the man in the outer office.
  • 66.
    CHAPTER VII THE PSYCHOLOGYOF PURCHASE There are several stages or phases manifested by the buyer in the mental process which results in a purchase. While it is difficult to state a hard and fast rule regarding the same, because of the variety of temperament, tendencies and mental habits possessed in several degrees by different individuals, still there are certain principles of feeling and thought manifested alike by each and every individual buyer, and a certain logical sequence is followed by all men in each and every original purchase. It follows, of course, that these principles, and this sequence, will be found to be operative in each and every original purchase, whether that purchase be the result of an advertisement, display of goods, recommendation, or the efforts of a salesman. The principle is the same in each and every case, and the sequence of the mental states is the same in each and every instance. Let us now consider these several mental states in their usual sequence. The several mental states manifested by every buyer in an original purchase are given below in the order of sequence in which they are usually manifested:— I. Involuntary Attention. II. First Impression. III. Curiosity. IV. Associated Interest. V. Consideration. VI. Imagination. VII. Inclination. VIII. Deliberation. IX. Decision.
  • 67.
    X. Action. We usethe term "original purchase" in this connection in order to distinguish the original purchase from a repeated order or subsequent purchase of the same article, in which latter instance the mental process is far more simple and which consists merely in recognizing the inclination, or habit, and ordering the goods, without repeating the original complex mental operation. Let us now proceed to a consideration of the several mental stages of the original purchase, in logical sequence:— I. Involuntary Attention. This mental state is the elementary phase of attention. Attention is not a faculty of the mind, but is instead the focusing of the consciousness upon one object to the temporary exclusion of all other objects. It is a turning of the mind on an object. The object of attention may be either external, such as a person or thing; or internal, such as a feeling, thought, memory, or idea. Attention may be either voluntary, that is, directed consciously by the will; or involuntary, that is, directed unconsciously and instinctively and apparently independently of the will. Voluntary attention is an acquired and developed power and is the attribute of the thinker, student and intellectual individual in all walks of life. Involuntary attention, on the contrary, is but little more than a reflex action, or a nervous response to some stimulus. As Halleck says: "Many persons scarcely get beyond the reflex stage. Any chance stimulus will take their attention away from their studies or their business." Sir William Hamilton made a still finer distinction, which is, however, generally overlooked by writers on the subject, but which is scientifically correct and which we shall follow in this book. He holds that there are three degrees or kinds of attention: (1) the reflex or involuntary, which is instinctive in nature; (2) that determined by desire or feeling, which partakes of both the involuntary and voluntary nature, and which although partly instinctive may be resisted by the will under the influence of the judgment; and (3) that determined by deliberate volition in response to reason, as in study, scientific games, rational deliberation, etc.
  • 68.
    The first mentalstep of the purchase undoubtedly consists of involuntary or reflex attention, such as is aroused by a sudden sound, sight, or other sensation. The degree of this involuntary attention depends upon the intensity, suddenness, novelty, or movement of the object to which it responds. All persons respond to the stimuli arousing this form of attention, but in different degrees depending upon the preoccupation or concentration of the individual at the time. The striking or novel appearance of an advertisement; the window-display of goods; the appearance of the salesman—all these things instinctively arouse the involuntary attention, and the buyer "turns his mind on" them. But this turning the mind on belongs to Hamilton's first class—that of the instinctive response to the sight or sound, and not that aroused by desire or deliberate thought. It is the most elemental form of attention or mental effort, and to the salesman means simply: "Well, I see you!" Sometimes the prospect is so preoccupied or concentrated on other things that he barely "sees" the salesman until an added stimulus is given by a direct remark. II. First Impression. This mental state is the hasty generalization resulting from the first impression of the object of attention—the advertisement, suggestion, display of goods, or the Salesman— depending in the last case upon the general appearance, action, manner, etc., as interpreted in the light of experience or association. In other words, the prospect forms a hasty general idea of the thing or person, either favorable or unfavorable, almost instinctively and unconsciously. The thing or person is associated or classed with others resembling it in the experience and memory of the prospect, and the result is either a good, bad or indifferent impression resulting from the suggestion of association. For this reason the ad. man and the window dresser endeavor to awaken favorable and pleasing associated memories and suggestions, and "puts his best foot foremost." The Salesman endeavors to do the same, and seeks to "put up a good front" in his Approach, in order to secure this valuable favorable first impression. People are influenced more than they will admit by these "first impressions," or suggestions, of
  • 69.
    appearance, manner, etc.,and the man who understands psychology places great importance upon them. A favorable first impression smooths the way for the successful awakening of the later mental states. An unfavorable first impression, while it may be removed and remedied later, nevertheless is a handicap which the Salesman should avoid. (Note: The mental process of the purchase now passes from the stage of involuntary attention, to that of attention inspired by desire and feeling which partakes of both the voluntary and involuntary elements. The first two stages of this form of attention are known as Curiosity and Associated Interest, respectively. In some cases Curiosity precedes, in others Associated Interest takes the lead, as we shall see. In other cases the manifestation of the two is almost simultaneous.) III. Curiosity. This mental state is really a form of Interest, but is more elemental than Associated Interest, being merely the interest of novelty. It is the strongest item of interest in the primitive races, in children, and in many adults of elemental development and habits of thought. Curiosity is the form of Interest which is almost instinctive, and which impels one to turn the attention to strange and novel things. All animals possess it to a marked degree, as trappers have found out to their profit. Monkeys possess it to an inordinate degree, and the less developed individuals of the human race also manifest it to a high degree. It is connected in some way with the primitive conditions of living things, and is probably a heritage from earlier and less secure conditions of living, where inquisitiveness regarding new, novel and strange sights and sounds was a virtue and the only means of acquiring experience and education. At any rate, there is certainly in human nature a decided instinctive tendency to explore the unknown and strange—the attraction of the mysterious; the lure of the secret things; the tantalizing call of the puzzle; the fascination of the riddle. The Salesman who can introduce something in his opening talk that will arouse Curiosity in the prospect has done much to arouse
  • 70.
    his attention andinterest. The street-corner fakir, and the "barker" for the amusement-park show, understand this principle in human nature, and appeal largely to it. They will blindfold a boy or girl, or will make strange motions or sounds, in order to arouse the curiosity of the crowd and to cause them to gather around—all this before the actual appeal to interest is made. In some buyers Curiosity precedes Associated Interest—the interest in the unknown and novel precedes the practical interest. In others the Associated Interest—the practical interest inspired by experience and association—precedes Curiosity, the latter manifesting simply as inquisitiveness regarding the details of the object which has aroused Associated Interest. In other cases, Curiosity and Associated Interest are so blended and shaded into each other that they act almost as one and simultaneously. On the whole, though, Curiosity is more elemental and crude than Associated Interest, and may readily be distinguished in the majority of cases. IV. Associated Interest. This mental state is a higher form of interest than Curiosity. It is a practical interest in things relating to one's interests in life, his weal or woe, loves or hates, instead of being the mere interest in novelty of Curiosity. It is an acquired trait, while Curiosity is practically an instinctive trait. Acquired Interest develops with character, occupation, and education, while Curiosity manifests strongly in the very beginnings of character, and before education. Acquired Interest is manifested more strongly in the man of affairs, education and experience, while Curiosity has its fullest flower in the monkey, savage, young child and uncultured adult. Recognizing the relation between the two, it may be said that Curiosity is the root, and Associated Interest the flower. Associated Interest depends largely upon the principle of Association or Apperception, the latter being defined as "that mental process by which the perceptions or ideas are brought into relation to our previous ideas and feelings, and thus are given a new clearness, meaning and application." Apperception is the mental process by which objects and ideas presented to us are perceived and thought of by us in the light of our past experience,
  • 71.
    temperament, tastes, likesand dislikes, occupation, interest, prejudices, etc., instead of as they actually are. We see everything through the colored glasses of our own personality and character. Halleck says of Apperception: "A woman may apperceive a passing bird as an ornament to her bonnet; a fruit grower, as an insect killer; a poet, as a songster; an artist, as a fine bit of coloring and form. The housewife may apperceive old rags as something to be thrown away; a ragpicker, as something to be gathered up. A carpenter, a botanist, an ornithologist, a hunter, and a geologist walking through a forest would not see the same things." The familiar tale of the text-books illustrates this principle. It relates that a boy climbed up a tree in a forest and watched the passers-by, and listened to their conversation. The first man said: "What a fine stick of timber that tree would make." The boy answered: "Good morning, Mr. Carpenter." The second man said: "That is fine bark." The boy answered: "Good morning, Mr. Tanner." The third man said: "I'll bet there's squirrels in that tree." The boy answered: "Good morning, Mr. Hunter." Each and every one of the men saw the tree in the light of his personal Apperception or Associated Interest. Psychologists designate by the term "the apperceptive mass" the accumulated previous experiences, prejudices, temperament, inclination and desires which serve to modify the new perception or idea. The "apperceptive mass" is really the "character" or "human nature" of the individual. It necessarily differs in each individual, by reason of the great variety of experiences, temperament, education, etc., among individuals. Upon a man's "apperceptive mass," or character, depends the nature and degree of his interest, and the objects which serve to inspire and excite it. It follows then that in order to arouse, induce and hold this Associated Interest of the prospect, the Salesman must present things, ideas or suggestions which will appeal directly to the imagination and feelings of the man before him, and which are associated with his desires, thoughts and habits. If we may be pardoned for the circular definition we would say that one's Associated Interest is aroused only by interesting things; and that
  • 72.
    the interesting thingsare those things which concern his interests. A man's interests always interest him—and his interests are usually those things which concern his advantage, success, personal well- being—in short his pocketbook, social position, hobbies, tastes, and satisfaction of his desires. Therefore the Salesman who can throw the mental spot-light on these interesting things, may secure and hold one's Associated Interest. Hence the psychology of the repeated statement: "I can save you money;" "I can increase your sales;" "I can reduce your expenses;" "I have something very choice;" or "I can give you a special advantage," etc. It may as well be conceded that business interest is selfish interest, and not altruistic. In order to interest a man in a business proposition he must be shown how it will benefit him in some way. He is not running a philanthropic institution, or a Salesman's Relief Fund, nor is he in business for his health—he is there to make money, and in order to interest him you must show him something to his advantage. And the first appeal of Associated Interest is to his feeling of Self Interest. It must be in the nature of the mention of "rats!" to a terrier, or "candy!" to a child. It must awaken pleasant associations in his mind, and pleasing images in his memory. If this effect is produced, he can be speedily moved to the succeeding phases of Imagination and Inclination. As Halleck says: "All feeling tends to excite desire. * * * A representative image of the thing desired is the necessary antecedent to desire. If the child had never seen or heard of peaches he would have no desire for them." And, following this same figure, we may say that if the child has a taste for peaches he will be interested in the idea of peaches. And so when you say "peaches!" to him you have his Associated Interest, which will result in a mental image of the fruit followed by a desire to possess it, and he will listen to your talk regarding the subject of "peaches." The following are the general psychological rules regarding Associated Interests:
  • 73.
    I. Associated Interestattaches only to interesting things—that is to things associated with one's general desires and ideas. II. Associated Interest will decline in force and effect unless some new attributes or features are presented—it requires variety in presentation of its object. Macbain says: "One of the old time salesmen who used to sell the trade in the Middle West, beginning some thirty years ago, and following that vocation for several decades, used as his motto, 'I am here to do you good.' He did not make his statement general, either, in telling his customers how he could do it. He got right down to the vital affairs which touched his customers. He demonstrated it to them, and this personal demonstration is the kind that makes the sales." Remember, always, that the phase of Associated Interest in a purchase is not the same as the phase of Demonstration and Proof. It is the "warming up" process, preceding the actual selling talk. It is the stage of "thawing out" the prospect and melting the icy covering of prejudice, caution and reluctance which encases him. Warm up your prospect by general statements of Associated Interest, and blow the coals by positive, brief, pointed confident statements of the good things you have in store for him. And, finally, remember that the sole purpose of your efforts at this state is to arouse in him the mental state of INTERESTED EXPECTANT ATTENTION! Keep blowing away at this spark until you obtain the blaze of Imagination and the heat of Desire. V. Consideration. This mental state is defined as: "An examination, inquiry, or investigation into anything." It is the stage following Curiosity and Associated Interest, and tends toward an inquiry into the thing which has excited these feelings. Consideration, of course, must be preceded and accompanied by Interest. It calls for the phase of Attention excited by feeling, but a degree of voluntary attention is also manifested therewith. It is the "I think I will look into this matter" stage of the mental process of purchase. It is usually evidenced by a disposition to ask questions regarding the
  • 74.
    proposition, and to"see what there is to it, anyway." In Salesmanship, this stage of Consideration marks the passing from the stage of Approach on the Salesman's part, to that of the Demonstration. It marks the passage from Passive Interest to Active Interest—from the stage of being "merely interested" in a thing, to that of "interested investigation." Here is where the real selling work of the salesman begins. Here is where he begins to describe his proposition in detail, laying stress upon its desirable points. In the case of an advertisement, or a window display, the mental operation goes on in the buyer's mind in the same way, but without the assistance of the salesman. The "selling talk" of the advertisement must be stated or suggested by its text. If the Consideration is favorable and reveals sufficiently strong attractive qualities in the proposition or article, the mind of the buyer passes on to the next stage of the process which is known as: VI. Imagination. This mental state is defined as: "The exercise of that power or faculty of the mind by which it conceives and forms ideal pictures of things communicated to it by the organs of sense." In the mental process of a purchase, the faculty of imagination takes up the idea of the object in which the Associated Interest has been aroused, and which has been made the subject of Consideration, and endeavors to picture the object in use and being employed in different ways, or as in possession of the buyer. One must use his imagination in order to realize what good a thing will be to him; how he may use it; how it will look; how it will sell; how it will serve its purpose; how it will "work out" or "make good" when purchased. A woman gazing at a hat will use her imagination to picture how she will look in it. The man looking at the book will use his imagination in picturing its uses and the pleasure to be derived therefrom. The business man will use his imagination to picture the probable sale of the goods, their display, their adaptability to his trade, etc. Another will picture himself enjoying the gains from his purchase. Imagination plays an important part in the psychology of the sale. It is the direct inciter of desire and inclination. The successful salesman realizes this, and feeds the flame of the imagination with the oil of
  • 75.
    Suggestion. In fact,Suggestion receives its power through the Imagination. The Imagination is the channel through which Suggestion reaches the mind. Salesmen and ad. writers strive to arouse the imagination of their prospective customers by clever word-painting. The Imagination is the "direct wire" to Desire. From Imagination it is a short step to the next mental stage which is called: VII. Inclination. This mental state is defined as: "A leaning or bent of the mind or will; desire; propensity." It is the "want to" feeling. It is the mental state of which Desire is an advanced stage. Inclination has many degrees. From a faint inclination or bent in a certain direction, it rises in the scale until it becomes an imperious demand, brooking no obstacle or hindrance. Many terms are employed to designate the various stages of Inclination, as for instance: Desire, wish, want, need, inclination, leaning, bent, predilection, propensity, penchant, liking, love, fondness, relish, longing, hankering, aspiration, ambition, appetite, hunger, passion, craving, lust, etc. Desire is a strange mental quality, and one very difficult to define strictly. It is linked with feeling on one side, and with will on the other. Feeling rises to desire, and desire rises to the phase of will and endeavors to express itself in action. Halleck says of Desire: "It has for its object something which will bring pleasure or get rid of pain, immediate or remote, for the individual or for some one in whom he is interested. Aversion, or a striving to get away from something, is merely the negative aspect of desire." Inclination in its various stages is aroused through the appeals to the feelings through the imagination. The feelings related to the several faculties are excited into action by a direct appeal to them through the imagination, and inclination or desired results. Appeal to Acquisitiveness will result in a feeling which will rise to inclination and desire for gain. Appeal to Approbativeness will act likewise in its own field. And so on through the list, each well-developed faculty being excited to feeling by the appropriate appeal through the imagination, and thus giving rise to Inclination which in turn strives to express itself in action through the will.
  • 76.
    In short, everyman is a bundle of general desires, the nature and extent of which are indicated by his several faculties, and which result from heredity, environment, training, experience, etc. These desires may be excited toward a definite object by the proper emotional appeal through the imagination, and by suggestion. Desire must be created or aroused before action can be had, or the will manifest in action. For, at the last, we do things only because we "want to," directly or indirectly. Therefore, the important aim of the Salesman is to make his prospect "want to." And in order to make him "want to" he must make him see that his proposition is calculated to "bring pleasure, or get rid of pain, immediate or remote, for the individual or for someone else in whom he is interested." In business, the words "profit and loss" may be substituted for "pleasure and pain," although really, they are but forms of the latter. But even when the prospect is brought to the stage of strong inclination or desire, he does not always move to gratify the same. Why is this? What other mental process interferes? Let us see as we pass on to the next stage of the purchase, known as: VIII. Deliberation. This mental state is defined as: "The act of deliberating and weighing facts and arguments in the mind, calmly and carefully." Here is manifested the action of thought and reason —the mental process of weighing and balancing facts, feelings, and inclinations. For it is not only facts and proofs which are weighed in the mental balance, but also feelings, desires, and fears. Pure logical reasoning inclines to strict logical processes based upon irrefragible facts, it is true—but there is but little pure logical reasoning. The majority of people are governed more by their feelings and inclinations—their loves and their fears—than by logic. It has been said: "People seek not reasons, but excuses for following their feelings." The real deliberation, in the majority of cases, is the weighing of probable advantages and disadvantages—of various likes and dislikes—of hopes and fears. It is said that our minds are controlled by motives—and the strongest motive wins. We often find that when we think we desire a
  • 77.
    thing ardently, wethen find that we also like something else better, or perhaps fear something else more than we desire the first thing. In such case, the strongest or most pressing feeling wins the day. The faculties here exert their different influences. Caution opposes Acquisitiveness. Acquisitiveness opposes Conscientiousness. Fear opposes Firmness. And so on. The deliberation is not only the weighing of facts, but also the weighing of feelings. The process of Deliberation—the weighing of desires—the play and counterplay of motives—is well illustrated by a scene in a classical French comedy. "Jeppe," one of the characters, has been given money by his wife to buy her a cake of soap. He prefers to buy a drink with the coin, for his inclinations tend in that direction. But he knows that his wife will beat him if he so squanders the money. He deliberates over the pleasure to be derived from the drink, and the pain which would arise from the beating. "My stomach says drink—my back says soap," says Jeppe. He deliberates further. Then: "My stomach says Yes! My back says No!" cries the poor wight. The conflict between back and stomach rages still more fiercely. Then comes the deciding point: "Is not my stomach more to me than my back? Sure, it is! I say Yes!" cries Jeppe. And away to the tavern he marches. It has been remarked that if the active suggestion of the distant sight of his wife armed with the cudgel, had been added to the situation, Jeppe would have bought the soap. Or, if the tavern had not been so handy, the result might have been different. Sometimes a mental straw tips the scale. The above illustration contains the entire philosophy of the action of the mind in the process of Deliberation. The salesman will do well to remember it. Halleck thus well states the immediate and remote factors in choice: "The immediate factors are * * * (1) a preceding process of desire; (2) the presence in consciousness of more than one represented object or end, to offer an alternative course of action; (3) deliberation concerning the respective merits of these objects; (4) the voluntary fiat of decision, which seems to embody most the very essence of will. The remote factors are extremely difficult to
  • 78.
    select. The sumtotal of the man is felt more in choice than anywhere else. * * * Before a second person could approximate the outcome, he would have to know certain remote factors, the principal being: (1) heredity; (2) environment; (3) education; (4) individual peculiarities." This eminent authority might well have added an additional element—a most important one—as follows: (5) SUGGESTION. The Salesman watching carefully the shifting scale of Deliberation, injects a telling argument or suggestion into the scale, which gives weight to his side at a critical stage. He does this in many ways. He may neutralize an objection by a counter-fact. He adds another proof or fact here—a little more desire and feeling there, until he brings down the scale to a decision. It must be remembered that this Deliberation is not regarding the desirability of the proposition— the prospect has admitted his desire, either directly or indirectly, and is now engaged in trying to justify his desire by reason and expediency. He is seeking for reasons or "excuses" to back up his desire, or perhaps, is endeavoring to strike a balance of his conflicting desires and feelings. His mental debate is not over the question of desiring the goods, but over the expediency and probable result of buying them. It is the "to buy or not to buy" stage. This is a delicate part of the process of the purchase, and many prospects act like "see-saws" during the process. The clever Salesman must be ready with the right argument at the right place. To him this is the Argumentive Stage. Finally, if the Salesman's efforts are successful, the balance drops, and the process passes to the next stage, known as— IX. Decision. This mental stage is defined as: "The mental act of deciding, determining, or settling any point, question, difference, or contest." It is the act of the will, settling the dispute between the warring faculties, feelings, ideas, desires and fears. It is will acting upon reason, or (alas! too often, upon mere feeling). Without entering into a metaphysical discussion, let us remind you that the practical psychology of the day holds that "the strongest motive at the moment wins the choice." This strongest motive may be of
  • 79.
    reason or offeeling; conscious or unconscious; but strongest at that moment it must be, or it would not win. And this strongest motive is strongest merely because of our character or "nature" as manifested at that particular moment, in that particular environment, under the particular circumstances, and subject to the particular suggestions. The choice depends more upon association than we generally realize, and association is awakened by suggestion. As Halleck says: "It is not the business of the psychologist to state what power the association of ideas ought to have. It is for him to ascertain what power it does have." And as Ziehen says: "We cannot think as we will, but we must think just as those associations which happen to be present prescribe." This being the case, the Salesman must realize that the Decision is based always upon (1) the mental states of the man at that moment; plus (2) the added motives supplied by the Salesman. It is "up to" the Salesman to supply those motives, whether they be facts, proofs, appeals to reason, or excitement of feeling. Hope, fear, like, dislike—these are the potent motives in most cases. In business, these things are known as "profit or loss." All the faculties of the mind supply motives which aroused may be thrown into the balance affecting decision. This is what argument, demonstration and appeal seek to do—supply motives. (Note:—It might naturally be supposed that when the final stage of Decision has been reached, the mental process of purchase is at an end. But, not so. Will has three phases: Desire, Decision, and Action. We have passed through the first two, but Action still is unperformed. A familiar example is that of the man in bed in the morning. He ponders over the question of rising, and finally decides to get up. But action does not necessarily result. The trigger of Action has not been pulled, and the spring released. So thus we have another mental state, known as:—) X. Action. This mental state is defined as: "Volition carried into effect." Mill says: "Now what is an action? Not one, but a series of two things: the state of mind called a volition, followed by an effect. The volition or intention to produce the effect is one thing; the effect produced in consequence of the intention is another thing; the two
  • 80.
    together constitute theaction." Halleck says: "For a completed act of will, there must be action along the line of the decision. Many a decision has not aroused the motor centers to action, nor quickened the attention, for any length of time. There are persons who can frame a dozen decisions in the course of a morning, and never carry out one of them. Sitting in a comfortable chair, it may take one but a very short time to form a decision that will require months of hard work. * * * Some persons can never seem to understand that resolving to do a thing is not the same as doing it. * * * There may be desire, deliberation, and decision; but if these do not result in action along the indicated line, the process of will is practically incomplete." Many a person decides to do a thing but lacks the something necessary to release the motive impulses. They tend to procrastinate, and delay the final act. These people are sources of great care and work to the Salesman. Some men can get their prospects to the deciding point, but fail to get them to act. Others seem specially adapted to "closing" these cases. It requires a peculiar knack to "close"—the effort is entirely psychological. We shall consider it in a subsequent chapter under the head of "Closing." To be a good "closer" is the ambition of every Salesman, for it is the best paid branch of his profession. It depends largely upon the scientific application of suggestion. To lead a prospect to Action, is to pull the trigger of his will. To this end all the previous work has been directed. Its psychology is subtle. What makes you finally get out of bed in the morning, after having "decided to" several times without resulting action? To understand this, is to understand the process of the final Action in the mind of the buyer. Is it not worth learning? In the succeeding chapters we shall consider the several stages of the "Salesman's Progress" toward a sale—the Approach, the Demonstration, and the Closing. In these stages of the Salesman, we shall see the action and reaction upon the Mind of the Buyer, along the lines of the Psychology of the Purchase. In the Sale- Purchase the minds of the Salesman and the Buyer meet. The result is the Signed Order. The psychological process of the Sale is akin to
  • 81.
    the progress ofa game of chess or checkers. And neither is the result of chance—well defined principles underlie each, and established methods are laid down for the student.
  • 82.
    Welcome to ourwebsite – the perfect destination for book lovers and knowledge seekers. We believe that every book holds a new world, offering opportunities for learning, discovery, and personal growth. That’s why we are dedicated to bringing you a diverse collection of books, ranging from classic literature and specialized publications to self-development guides and children's books. More than just a book-buying platform, we strive to be a bridge connecting you with timeless cultural and intellectual values. With an elegant, user-friendly interface and a smart search system, you can quickly find the books that best suit your interests. Additionally, our special promotions and home delivery services help you save time and fully enjoy the joy of reading. Join us on a journey of knowledge exploration, passion nurturing, and personal growth every day! ebookbell.com