100% found this document useful (3 votes)
13 views

Data Structures & Algorithms in Python 1st Edition John Canning - eBook PDF download

The document provides information about the eBook 'Data Structures & Algorithms in Python' by John Canning, including links for downloading and additional recommended eBooks. It outlines the contents of the book, which covers various data structures and algorithms, and includes sections on arrays, sorting, trees, graphs, and more. The document also emphasizes Pearson's commitment to diversity, equity, and inclusion in educational content.

Uploaded by

phioporkar
Copyright
© © All Rights Reserved
Available Formats
Download as PDF, TXT or read online on Scribd
100% found this document useful (3 votes)
13 views

Data Structures & Algorithms in Python 1st Edition John Canning - eBook PDF download

The document provides information about the eBook 'Data Structures & Algorithms in Python' by John Canning, including links for downloading and additional recommended eBooks. It outlines the contents of the book, which covers various data structures and algorithms, and includes sections on arrays, sorting, trees, graphs, and more. The document also emphasizes Pearson's commitment to diversity, equity, and inclusion in educational content.

Uploaded by

phioporkar
Copyright
© © All Rights Reserved
Available Formats
Download as PDF, TXT or read online on Scribd
You are on page 1/ 61

Data Structures & Algorithms in Python 1st

Edition John Canning - eBook PDF pdf download

https://ebooksecure.com/download/data-structures-algorithms-in-
python-ebook-pdf/

Download more ebook from https://ebooksecure.com


We believe these products will be a great fit for you. Click
the link to download now, or visit ebooksecure.com
to discover even more!

Data Structures & Algorithms in Python 1st Edition John


Canning - eBook PDF

https://ebooksecure.com/download/data-structures-algorithms-in-
python-ebook-pdf/

Fundamentals Of Python: Data Structures 2nd Edition


Kenneth A. Lambert - eBook PDF

https://ebooksecure.com/download/fundamentals-of-python-data-
structures-ebook-pdf/

Data Structures - eBook PDF

https://ebooksecure.com/download/data-structures-ebook-pdf/

(eBook PDF) Data Structures & Algorithm Analysis in C++


4th Edition

http://ebooksecure.com/product/ebook-pdf-data-structures-
algorithm-analysis-in-c-4th-edition/
Data Structures & Algorithm Analysis in C++ 4th Edition
(eBook PDF)

http://ebooksecure.com/product/data-structures-algorithm-
analysis-in-c-4th-edition-ebook-pdf/

Introduction to Algorithms for Data Mining and Machine


Learning 1st edition - eBook PDF

https://ebooksecure.com/download/introduction-to-algorithms-for-
data-mining-and-machine-learning-ebook-pdf/

Machine Learning for Biometrics: Concepts, Algorithms


and Applications (Cognitive Data Science in Sustainable
Computing) 1st Edition - eBook PDF

https://ebooksecure.com/download/machine-learning-for-biometrics-
concepts-algorithms-and-applications-cognitive-data-science-in-
sustainable-computing-ebook-pdf/

Data Structures and Applications: A Simple and


Systematic Approach 1st edition - eBook PDF

https://ebooksecure.com/download/data-structures-and-
applications-a-simple-and-systematic-approach-ebook-pdf/

(eBook PDF) Starting Out with Java: From Control


Structures through Data Structures 3rd Edition

http://ebooksecure.com/product/ebook-pdf-starting-out-with-java-
from-control-structures-through-data-structures-3rd-edition/
Data Structures & Algorithms in Python
Data Structures & Algorithms in
Python

John Canning
Alan Broder
Robert Lafore

Boston • Columbus • New York • San Francisco • Amsterdam • Cape Town


Dubai • London • Madrid • Milan • Munich • Paris • Montreal • Toronto • Delhi • Mexico City
São Paulo • Sidney • Hong Kong • Seoul • Singapore • Taipei • Tokyo
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 the publisher was aware of a
trademark claim, the designations have been printed with initial capital letters or in all capitals.
The authors and publisher have taken care in the preparation of this book, but make no expressed or
implied warranty of any kind and assume no responsibility for errors or omissions. No liability is
assumed for incidental or consequential damages in connection with or arising out of the use of the
information or programs contained herein.
For information about buying this title in bulk quantities, or for special sales opportunities (which
may include electronic versions; custom cover designs; and content particular to your business,
training goals, marketing focus, or branding interests), please contact our corporate sales department
at [email protected] or (800) 382-3419.
For government sales inquiries, please contact [email protected].
For questions about sales outside the U.S., please contact [email protected].
Visit us on the Web: informit.com/aw
Library of Congress Control Number: 2022910068
Copyright © 2023 Pearson Education, Inc.
All rights reserved. Printed in the United States of America. This publication is protected by
copyright, and permission must be obtained from the publisher prior to any prohibited reproduction,
storage in a retrieval system, or transmission in any form or by any means, electronic, mechanical,
photocopying, recording, or likewise. For information regarding permissions, request forms and the
appropriate contacts within the Pearson Education Global Rights & Permissions Department, please
visit www.pearsoned.com/permissions/.
ISBN-13: 978-0-13-485568-4
ISBN-10: 0-13-485568-X
ScoutAutomatedPrintCode
Editor-in-Chief
Mark Taub
Director, ITP Product Management
Brett Bartow
Acquisitions Editor
Kim Spenceley
Development Editor
Chris Zahn
Managing Editor
Sandra Schroeder
Project Editor
Mandie Frank
Copy Editor
Chuck Hutchinson
Indexer
Proofreader
Editorial Assistant
Cindy Teeters
Designer
Chuti Prasertsith
Compositor
codeMantra
Pearson’s Commitment to
Diversity, Equity, and Inclusion
Pearson is dedicated to creating bias-free content that reflects the diversity
of all learners. We embrace the many dimensions of diversity, including but
not limited to race, ethnicity, gender, socioeconomic status, ability, age,
sexual orientation, and religious or political beliefs.
Education is a powerful force for equity and change in our world. It has the
potential to deliver opportunities that improve lives and enable economic
mobility. As we work with authors to create content for every product and
service, we acknowledge our responsibility to demonstrate inclusivity and
incorporate diverse scholarship so that everyone can achieve their potential
through learning. As the world’s leading learning company, we have a duty
to help drive change and live up to our purpose to help more people create a
better life for themselves and to create a better world.
Our ambition is to purposefully contribute to a world where
• Everyone has an equitable and lifelong opportunity to succeed
through learning
• Our educational products and services are inclusive and represent the
rich diversity of learners
• Our educational content accurately reflects the histories and
experiences of the learners we serve
• Our educational content prompts deeper discussions with learners and
motivates them to expand their own learning (and worldview)
While we work hard to present unbiased content, we want to hear from you
about any concerns or needs with this Pearson product so that we can
investigate and address them.
Please contact us with concerns about any potential bias at
https://www.pearson.com/report-bias.html.
To my mother, who gave me a thirst for knowledge, to my father, who
taught me the joys of engineering, and to June, who made it possible to
pursue both.

John Canning

For my father Sol Broder, a computer science pioneer, who inspired me to


follow in his footsteps.

To my mother Marilyn Broder, for showing me the satisfaction of teaching


others.

To Fran, for making my life complete.

Alan Broder
Contents
1. Overview

2. Arrays

3. Simple Sorting

4. Stacks and Queues

5. Linked Lists

6. Recursion

7. Advanced Sorting

8. Binary Trees

9. 2-3-4 Trees and External Storage

10. AVL and Red-Black Trees

11. Hash Tables

12. Spatial Data Structures

13. Heaps

14. Graphs

15. Weighted Graphs

16. What to Use and Why


Appendix A. Running the Visualizations

Appendix B. Further Reading

Appendix C. Answers to Questions


Table of Contents
1. Overview
What Are Data Structures and Algorithms?
Overview of Data Structures
Overview of Algorithms
Some Definitions
Programming in Python
Object-Oriented Programming
Summary
Questions
Experiments

2. Arrays
The Array Visualization Tool
Using Python Lists to Implement the Array Class
The Ordered Array Visualization Tool
Python Code for an Ordered Array Class
Logarithms
Storing Objects
Big O Notation
Why Not Use Arrays for Everything?
Summary
Questions
Experiments
Programming Projects

3. Simple Sorting
How Would You Do It?
Bubble Sort
Selection Sort
nsertion Sort
Comparing the Simple Sorts
Summary
Questions
Experiments
Programming Projects

4. Stacks and Queues


Different Structures for Different Use Cases
Stacks
Queues
Priority Queues
Parsing Arithmetic Expressions
Summary
Questions
Experiments
Programming Projects

5. Linked Lists
Links
The Linked List Visualization Tool
A Simple Linked List
Linked List Efficiency
Abstract Data Types and Objects
Ordered Lists
Doubly Linked Lists
Circular Lists
terators
Summary
Questions
Experiments
Programming Projects
6. Recursion
Triangular Numbers
Factorials
Anagrams
A Recursive Binary Search
The Tower of Hanoi
Sorting with mergesort
Eliminating Recursion
Some Interesting Recursive Applications
Summary
Questions
Experiments
Programming Projects

7. Advanced Sorting
Shellsort
Partitioning
Quicksort
Degenerates to O(N2) Performance
Radix Sort
Timsort
Summary
Questions
Experiments
Programming Projects

8. Binary Trees
Why Use Binary Trees?
Tree Terminology
An Analogy
How Do Binary Search Trees Work?
Finding a Node
nserting a Node
Traversing the Tree
Finding Minimum and Maximum Key Values
Deleting a Node
The Efficiency of Binary Search Trees
Trees Represented as Arrays
Printing Trees
Duplicate Keys
The BinarySearchTreeTester.py Program
The Huffman Code
Summary
Questions
Experiments
Programming Projects

9. 2-3-4 Trees and External Storage


ntroduction to 2-3-4 Trees
The Tree234 Visualization Tool
Python Code for a 2-3-4 Tree
Efficiency of 2-3-4 Trees
-3 Trees
External Storage
Summary
Questions
Experiments
Programming Projects

10. AVL and Red-Black Trees


Our Approach to the Discussion
Balanced and Unbalanced Trees
AVL Trees
The Efficiency of AVL Trees
Red-Black Trees
Using the Red-Black Tree Visualization Tool
Experimenting with the Visualization Tool
Rotations in Red-Black Trees
nserting a New Node
Deletion
The Efficiency of Red-Black Trees
-3-4 Trees and Red-Black Trees
Red-Black Tree Implementation
Summary
Questions
Experiments
Programming Projects

11. Hash Tables


ntroduction to Hashing
Open Addressing
Separate Chaining
Hash Functions
Hashing Efficiency
Hashing and External Storage
Summary
Questions
Experiments
Programming Projects

12. Spatial Data Structures


Spatial Data
Computing Distances Between Points
Circles and Bounding Boxes
Searching Spatial Data
Lists of Points
Grids
Quadtrees
Theoretical Performance and Optimizations
Practical Considerations
Further Extensions
Summary
Questions
Experiments
Programming Projects

13. Heaps
ntroduction to Heaps
The Heap Visualization Tool
Python Code for Heaps
A Tree-Based Heap
Heapsort
Order Statistics
Summary
Questions
Experiments
Programming Projects

14. Graphs
ntroduction to Graphs
Traversal and Search
Minimum Spanning Trees
Topological Sorting
Connectivity in Directed Graphs
Summary
Questions
Experiments
Programming Projects

15. Weighted Graphs


Minimum Spanning Tree with Weighted Graphs
The Shortest-Path Problem
The All-Pairs Shortest-Path Problem
Efficiency
ntractable Problems
Summary
Questions
Experiments
Programming Projects

16. What to Use and Why


Analyzing the Problem
Foundational Data Structures
Special-Ordering Data Structures
Sorting
Specialty Data Structures
External Storage
Onward

Appendix A. Running the Visualizations


For Developers: Running and Changing the Visualizations
For Managers: Downloading and Running the Visualizations
For Others: Viewing the Visualizations on the Internet
Using the Visualizations

Appendix B. Further Reading


Data Structures and Algorithms
Object-Oriented Programming Languages
Object-Oriented Design (OOD) and Software Engineering

Appendix C. Answers to Questions


Chapter 1, “Overview”
Chapter 2, “Arrays”
Chapter 3, “Simple Sorting”
Chapter 4, “Stacks and Queues”
Chapter 5, “Linked Lists”
Chapter 6, “Recursion”
Chapter 7, “Advanced Sorting”
Chapter 8, “Binary Trees”
Chapter 9, “2-3-4 Trees and External Storage”
Chapter 10, “AVL and Red-Black Trees”
Chapter 11, “Hash Tables”
Chapter 12, “Spatial Data Structures”
Chapter 13, “Heaps”
Chapter 14, “Graphs”
Chapter 15, “Weighted Graphs”
Register your copy of Data Structures & Algorithms in Python at
informit.com for convenient access to downloads, updates, and corrections
as they become available. To start the registration process, go to
informit.com/register and log in or create an account. Enter the product
ISBN 9780134855684 and click Submit. Once the process is complete, you
will find any available bonus content under “Registered Products.”
Acknowledgments
From John Canning and Alan Broder
Robert Lafore’s Java-based version of this book has been a mainstay in
Data Structures courses and professionals’ reference shelves around the
world for many years. When Alan’s Data Structures course at Stern College
for Women of Yeshiva University moved on to Python, the inability to use
Lafore’s book in the course was a real loss. We’re thus especially happy to
bring this new and revised edition to the world of Python programmers and
students.
We’d like to thank the many students at Stern who contributed to this book
either directly or indirectly over the past several years. Initial Python
versions of Lafore’s Java implementations were central to Alan’s Python-
based courses, and Stern student feedback helped improve the code’s
clarity, enhanced its performance, and sometimes even identified and fixed
bugs!
For their valuable feedback and recommendations on early drafts of this
new edition, we are grateful to many students in Alan’s Data Structures
courses, including Estee Brooks, Adina Bruce, Julia Chase, Hanna Fischer,
Limor Kohanim, Elisheva Kohn, Shira Orlian, Shira Pahmer, Jennie Peled,
Alexandra Roffe, Avigail Royzenberg, Batia Segal, Penina Waghalter, and
Esther Werblowsky. Our apologies if we’ve omitted anyone’s name.
An open-source package of data structure visualizations is available to
enhance your study of this book, and Stern students played an active role in
the development of the visualization software. John and Alan extend many
thanks to the Stern student pioneers and leaders of this project, including
Ilana Radinsky, Elana Apfelbaum, Ayliana Teitelbaum, and Lily Polonetsky,
as well as the following past and present Stern student contributors: Zoe
Abboudi, Ayelet Aharon, Lara Amar, Natania Birnbaum, Adina Bruce,
Chani Dubin, Sarah Engel, Sarah Graff, Avigayil Helman, Michal
Kaufman, Sarina Kofman, Rachel Leiser, Talia Leitner, Shani Lewis, Rina
Melincoff, Atara Neugroschl, Shira Pahmer, Miriam Rabinovich, Etta Rapp,
Shira Sassoon, Mazal Schoenwald, Shira Schneider, Shira Smith, Riva
Tropp, Alexandra Volchek, and Esther Werblowsky. Our apologies if we
have left anyone off this list.
Many thanks go to Professor David Matuszek of the University of
Pennsylvania for his early contributions of ideas and PowerPoint slides
when Alan first started teaching Data Structures at Stern. Many of the slides
available in the Instructors Resources section have their origin in his clear
and well-designed slides. Also, we are grateful to Professor Marian Gidea
of the Department of Mathematics of Yeshiva University for his insights
into spherical trigonometry.
Finally, we owe a great debt to the talented editors at Pearson who made
this book a reality: Mark Taber, Kim Spenceley, Mandie Frank, and Chris
Zahn. Without their many talents and patient help, this project would just be
an odd collection of text files, drawings, and source code.
From Robert Lafore for the Java-based versions of the book

Acknowledgments to the First Edition


My gratitude for the following people (and many others) cannot be fully
expressed in this short acknowledgment. As always, Mitch Waite had the
Java thing figured out before anyone else. He also let me bounce the applets
off him until they did the job, and extracted the overall form of the project
from a miasma of speculation. My editor, Kurt Stephan, found great
reviewers, made sure everyone was on the same page, kept the ball rolling,
and gently but firmly ensured that I did what I was supposed to do. Harry
Henderson provided a skilled appraisal of the first draft, along with many
valuable suggestions. Richard S. Wright, Jr., as technical editor, corrected
numerous problems with his keen eye for detail. Jaime Niño, Ph.D., of the
University of New Orleans, attempted to save me from myself and
occasionally succeeded, but should bear no responsibility for my approach
or coding details. Susan Walton has been a staunch and much-appreciated
supporter in helping to convey the essence of the project to the
nontechnical. Carmela Carvajal was invaluable in extending our contacts
with the academic world. Dan Scherf not only put the CD-ROM together,
but was tireless in keeping me up to date on rapidly evolving software
changes. Finally, Cecile Kaufman ably shepherded the book through its
transition from the editing to the production process.

Acknowledgments to the Second Edition


My thanks to the following people at Sams Publishing for their competence,
effort, and patience in the development of this second edition. Acquisitions
Editor Carol Ackerman and Development Editor Songlin Qiu ably guided
this edition through the complex production process. Project Editor Matt
Purcell corrected a semi-infinite number of grammatical errors and made
sure everything made sense. Tech Editor Mike Kopak reviewed the
programs and saved me from several problems. Last but not least, Dan
Scherf, an old friend from a previous era, provides skilled management of
my code and applets on the Sams website.
About the Author
Dr. John Canning is an engineer, computer scientist, and researcher. He
earned an S.B. degree in electrical engineering from the Massachusetts
Institute of Technology and a Ph.D. in Computer Science from the
University of Maryland at College Park. His varied professions include
being a professor of computer science, a researcher and software engineer
in industry, and a company vice president. He now is president of
Shakumant Software.
Alan Broder is clinical professor and chair of the Department of Computer
Science at Stern College for Women of Yeshiva University in New York
City. He teaches introductory and advanced courses in Python
programming, data structures, and data science. Before joining Stern
College, he was a software engineer, designing and building large-scale
data analysis systems. He founded and led White Oak Technologies, Inc. as
its CEO, and later served as the chairman and fellow of its successor
company, Novetta, in Fairfax, Virginia.
Introduction
What’s in this book? This book is designed to be a practical introduction to
data structures and algorithms for students who have just begun to write
computer programs. This introduction will tell you more about the book,
how it is organized, what experience we expect readers will have before
starting the book, and what knowledge you will get by reading it and doing
the exercises.

Who This Book Is For


Data structures and algorithms are the core of computer science. If you’ve
ever wanted to understand what computers can do, how they do it, and what
they can’t do, then you need a deep understanding of both (it’s probably
better to say “what computers have difficulty doing” instead of what they
can’t do). This book may be used as a text in a data structures and/or
algorithms course, frequently taught in the second year of a university
computer science curriculum. The text, however, is also designed for
professional programmers, for high school students, and for anyone else
who needs to take the next step up from merely knowing a programming
language. Because it’s easy to understand, it is also appropriate as a
supplemental text to a more formal course. It is loaded with examples,
exercises, and supplemental materials, so it can be used for self-study
outside of a classroom setting.
Our approach in writing this book is to make it easy for readers to
understand how data structures operate and how to apply them in practice.
That’s different from some other texts that emphasize the mathematical
theory, or how those structures are implemented in a particular language or
software library. We’ve selected examples with real-world applications and
avoid using math-only or obscure examples. We use figures and
visualization programs to help communicate key ideas. We still cover the
complexity of the algorithms and the math needed to show how complexity
impacts performance.

What You Need to Know Before You Read This


Book
The prerequisites for using this book are: knowledge of some programming
language and some mathematics. Although the sample code is written in
Python, you don’t need to know Python to follow what’s happening. Python
is not hard to understand, if you’ve done some procedural and/or object-
oriented programming. We’ve kept the syntax in the examples as general as
possible,
More specifically, we use Python version 3 syntax. This version differs
somewhat from Python 2, but not greatly. Python is a rich language with
many built-in data types and libraries that extend its capabilities. Our
examples, however, use the more basic constructs for two reasons: it makes
them easier to understand for programmers familiar with other languages,
and it illustrates the details of the data structures more explicitly. In later
chapters, we do make use of some Python features not found in other
languages such as generators and list comprehensions. We explain what
these are and how they benefit the programmer.
Of course, it will help if you’re already familiar with Python (version 2 or
3). Perhaps you’ve used some of Python’s many data structures and are
curious about how they are implemented. We review Python syntax in
Chapter 1, “Overview,” for those who need an introduction or refresher. If
you’ve programmed in languages like Java, C++, C#, JavaScript, or Perl,
many of the constructs should be familiar. If you’ve only programmed
using functional or domain-specific languages, you may need to spend more
time becoming familiar with basic elements of Python. Beyond this text,
there are many resources available for novice Python programmers,
including many tutorials on the Internet.
Besides a programming language, what should every programmer know? A
good knowledge of math from arithmetic through algebra is essential.
Computer programming is symbol manipulation. Just like algebra, there are
ways of transforming expressions to rearrange terms, put them in different
forms, and make certain parts more prominent, all while preserving the
same meaning. It’s also critical to understand exponentials in math. Much
of computer science is based on knowing what raising one number to a
power of another means. Beyond math, a good sense of organization is also
beneficial for all programming. Knowing how to organize items in different
ways (by time, by function, by size, by complexity, and so on) is crucial to
making programs efficient and maintainable. When we talk about efficiency
and maintainability, they have particular meanings in computer science.
Efficiency is mostly about how much time it takes to compute things but can
also be about the amount of space it takes. Maintainability refers to the ease
of understanding and modifying your programs by other programmers as
well as yourself.
You’ll also need knowledge of how to find things on the Internet, download
and install software, and run them on a computer. The instructions for
downloading and running the visualization programs can be found in
Appendix A of this book. The Internet has made it very easy to access a
cornucopia of tools, including tools for learning programming and
computer science. We expect readers to already know how to find useful
resources and avoid sources that might provide malicious software.

What You Can Learn from This Book


As you might expect from its title, this book can teach you about how data
structures make programs (and programmers) more efficient in their work.
You can learn how data organization and its coupling with appropriate
algorithms greatly affect what can be computed with a given amount of
computing resources. This book can give you a thorough understanding of
how to implement the data structures, and that should enable you to
implement them in any programming language. You can learn the process
of deciding what data structure(s) and algorithms are the most appropriate
to meet a particular programming request. Perhaps most importantly, you
can learn when an algorithm and/or data structure will fail in a given use
case. Understanding data structures and algorithms is the core of computer
science, which is different from being a Python (or other language)
programmer.
The book teaches the fundamental data structures that every programmer
should know. Readers should understand that there are many more. These
basic data structures work in a wide variety of situations. With the skills
you develop in this book, you should be able to read a description of
another data structure or algorithm and begin to analyze whether or not it
will outperform or perform worse than the ones you’ve already learned in
particular use cases.
This book explains some Python syntax and structure, but it will not teach
you all its capabilities. The book uses a subset of Python’s full capabilities
to illustrate how more complex data structures are built from the simpler
constructs. It is not designed to teach the basics of programming to
someone who has never programmed. Python is a very high-level language
with many built-in data structures. Using some of the more primitive types
such as arrays of integers or record structures, as you might find in C or
C++, is somewhat more difficult in Python. Because the book’s focus is the
implementation and analysis of data structures, our examples use
approximations to these primitive types. Some Python programmers may
find these examples unnecessarily complex, knowing about the more
elegant constructs provided with the language in standard libraries. If you
want to understand computer science, and in particular, the complexity of
algorithms, you must understand the underlying operations on the
primitives. When you use a data structure provided in a programming
language or from one of its add-on modules, you will often have to know its
complexity to know whether it will work well for your use case.
Understanding the core data structures, their complexities, and trade-offs
will help you understand the ones built on top of them.
All the data structures are developed using object-oriented programming
(OOP). If that’s a new concept for you, the review in Chapter 1 of how
classes are defined and used in Python provides a basic introduction to
OOP. You should not expect to learn the full power and benefits of OOP
from this text. Instead, you will learn to implement each data structure as a
class. These classes are the types of objects in OOP and make it easier to
develop software that can be reused by many different applications in a
reliable way.
The book uses many examples, but this is not a book about a particular
application area of computer science such as databases, user interfaces, or
artificial intelligence. The examples are chosen to illustrate typical
applications of programs, but all programs are written in a particular
context, and that changes over time. A database program written in 1970
may have appeared very advanced at that time, but it might seem very
trivial today. The examples presented in this text are designed to teach how
data structures are implemented, how they perform, and how to compare
them when designing a new program. The examples should not be taken as
the most comprehensive or best implementation possible of each data
structure, nor as a thorough review of all the potential data structures that
could be appropriate for a particular application area.

Structure
Each chapter presents a particular group of data structures and associated
algorithms. At the end of the chapters, we provide review questions
covering the key points in the chapter and sometimes relationships to
previous chapters. The answers for these can be found in Appendix C,
“Answers to Questions.” These questions are intended as a self-test for
readers, to ensure you understood all the material.
Many chapters suggest experiments for readers to try. These can be
individual thought experiments, team assignments, or exercises with the
software tools provided with the book. These are designed to apply the
knowledge just learned to some other area and help deepen your
understanding.
Programming projects are longer, more challenging programming exercises.
We provide a range of projects of different levels of difficulty. These
projects might be used in classroom settings as homework assignments.
Sample solutions to the programming projects are available to qualified
instructors from the publisher.

History
Mitchell Waite and Robert Lafore developed the first version of this book
and titled it Data Structures and Algorithms in Java. The first edition was
published in 1998, and the second edition, by Robert, came out in 2002.
John Canning and Alan Broder developed this version using Python due to
its popularity in education and commercial and noncommercial software
development. Java is widely used and an important language for computer
scientists to know. With many schools adopting Python as a first
programming language, the need for textbooks that introduce new concepts
in an already familiar language drove the development of this book. We
expanded the coverage of data structures and updated many of the
examples.
We’ve tried to make the learning process as painless as possible. We hope
this text makes the core, and frankly, the beauty of computer science
accessible to all. Beyond just understanding, we hope you find learning
these ideas fun. Enjoy yourself!
1. Overview
You have written some programs and learned enough to think that
programming is fun, or at least interesting. Some parts are easy, and some parts
are hard. You’d like to know more about how to make the process easier, get
past the hard parts, and conquer more complex tasks. You are starting to study
the heart of computer science, and that brings up many questions. This chapter
sets the stage for learning how to make programs that work properly and fast. It
explains a bunch of new terms and fills in background about the programming
language that we use in the examples.

In This Chapter
• What Are Data Structures and Algorithms?
• Overview of Data Structures
• Overview of Algorithms
• Some Definitions
• Programming in Python
• Object-Oriented Programming

What Are Data Structures and Algorithms?


Data organizations are ways data is arranged in the computer using its various
storage media (such as random-access memory, or RAM, and disk) and how
that data is interpreted to represent something. Algorithms are the procedures
used to manipulate the data in these structures. The way data is arranged can
simplify the algorithms and make algorithms run faster or slower. Together, the
data organization and the algorithm form a data structure. The data structures
Another Random Scribd Document
with Unrelated Content
that was unusual to it; but suppressing his feelings, he replied in his
accustomed tone,
“I was up all night, Master Charles, helping to reef top-sails, and
lending a hand to get up the new fore-sail in place of the old one
that was blown out of the bolt-ropes in the mid-watch. This morning
I could not sleep, for you know I was playing with you until mess-
time.”
“Well, Tom, come into the cabin and let’s play, and I wont say
any thing about it this time,” said Charles, as he walked in, followed
by his companion.
What a difference there was between the apartment in which the
lads now were, and the one which Tom had left but a few moments
before. It was the difference between wealth and poverty.
The vessel, on board of which our scene is laid, was a new and
magnificently-finished barque of seven hundred and fifty tons,
named the Josephine. The craft had been built to order, and was
owned and commanded by Lewis Barney Andrews—a gentleman of
education and extensive fortune, who had been for many years an
officer in the United States navy. Getting married, however, and his
wife’s objecting to the long cruises he was obliged to take in the
service, whilst she was compelled to remain at home, he effected a
compromise between his better half’s desire that he should
relinquish his profession, and his own disinclination to give up going
to sea entirely, by resigning his commission in the navy, and
purchasing a ship for himself. The Josephine belonged to Baltimore—
of which city Captain A. was a native, and was bound to the East
Indies. She was freighted with a valuable cargo, which also belonged
to the captain, and had on board besides the captain, his wife, son
and servant-girl, a crew consisting of two mates, and a boatswain,
fourteen seamen, a cook, steward, and one boy.
Her cabin—a poop one—was fitted up in the most luxurious style.
Every thing that the skill of the upholsterer and the art of the
painter, aided by the taste and experience of the captain, could do to
make it elegant, beautiful and comfortable, had been done.
Extending nearly to the main-mast the distance from the cabin-door
to the transom was full fifty feet. This space was divided into two
apartments of unequal size, one of twenty, the other thirty feet, by a
sliding bulkhead of highly polished rosewood and superbly-stained
glass.
The after-cabin was fitted up as a sleeping-room, with two
mahogany bedsteads and all the appurtenances found in the
chambers of the wealthy on shore. The forward-cabin was used as a
sitting and eating-room. On the floor was a carpet, of whose fabric
the looms of Persia might be proud—so rich, so thick, so magnificent
was it, and deep-cushioned ottomans, lounges and rocking-chairs
were scattered along the sides and were placed in the corners of the
apartment.
Not far from the door, reclining on a lounge, with a book in her
hand, was the wife of the captain, and the mother of Master Charles.
She was a handsome woman, but one who had ever permitted her
fancies and her feelings to be the guides of her actions.
Consequently her heart, which by nature was a kind one, was often
severely wrung by the pangs of remorse, caused by the recollection
of deeds committed from impulse, which her pride would not permit
her to apologize or atone for, even after she was convinced of her
error.
As the two boys entered the cabin she looked at them, but
without making any remark, continued the perusal of her book,
whilst they proceeded to the after-cabin, and getting behind the
bulkhead were out of her sight. For some fifteen minutes the
stillness of the cabin was undisturbed; but then, the mother’s
attention was attracted by the loud, angry tones of her son’s voice,
abusing apparently his play-fellow. Hardly had she commenced
listening, to ascertain what was the matter, ere the sound of a blow,
followed by a shriek, and the fall of something heavy upon the floor,
reached her ear. Alarmed, she rushed into the after-cabin, and there,
upon the floor, his face covered with blood, she saw the idol of her
heart, the one absorbing object of her affection, her only son, and
standing over him, with flashing eyes, swelling chest, and clenched
fists, the sailor-boy.
So strong was the struggle between the emotions of love and
revenge—a desire to assist her child, a disposition to punish his
antagonist—that the mother for a moment stood as if paralyzed.
Love, however, assumed the mastery; and raising her son and
pressing him to her bosom, she asked in most tender tones, “Where
he was hurt?”
“I ain’t hurt, only my nose is bleeding because Tom knocked me
down, just for nothing at all,” blubbered out Charles.
The mother’s anxiety for her son relieved, the tiger in her
disposition resumed the sway; letting go of Charles, she caught hold
of Tom, and shaking him violently, demanded, in shrill, fierce tones,
how he, the outcast, dared to strike her child!
Unabashed and unterrified, the sailor-boy looked in the angry
woman’s face without replying.
“Why don’t you answer me, you cub! you wretch! you little
pirate!—speak! speak! or I’ll shake you to death!” continued the
lady, incensed more than ever by the boy’s silence.
“I struck him because he called my mother a hussy, if you will
make me tell you,” replied Tom, in a quiet voice, though his eye was
bright with anger and insulted pride.
“Your mother a hussy! Well, what else was she? But you shall be
taught how to strike your master for speaking the truth to you, you
good for nothing vagabond. Run and call your father,” she continued,
turning to Charles, “and I’ll have this impertinent little rascal
whipped until he can’t stand.”
In a moment Captain Andrews entered; and being as much
incensed as his wife, that a sailor-boy, a thing he had always looked
upon as little better than a block or rope’s end, had had the audacity
to strike his son, he was furious. Taking hold of Tom with a rough
grasp, he pushed him out on deck, and called for the boatswain.
That functionary, however, was slow in making his appearance; and
again, in louder and more angry tones, the captain called for him.
Still he came not; and, spite of his passion, the captain could but
gather from the lowering expressions of the sailors’ countenances,
that he was at the commencement of an emeute.
[1] Colt.—A rope with a knot on the end. Used as an
instrument of punishment in place of the cat-o’-
nine-tails.

——
CHAPTER II.
The deepest ice that ever froze
Can only o’er the surface close;
The living stream lies quick below,
And flows, and cannot cease to flow.
Byron.

Accustomed to have his commands always promptly obeyed, the


wrath of Captain Andrews waxed high and furious at the dilatoriness
of the boatswain. Without any other exciting cause, this apparent
insubordination on the part of one of his officers, was enough to
arouse all the evil passions of his heart. Educated under the strict
discipline of the United States service, he had been taught that the
first and most important duty of a seaman was obedience. “Obey
orders, if you break owners,” was the doctrine he inculcated; and to
be thus, as it were, bearded on his own quarter-deck, by one of his
own men, was something entirely new, and most insulting to his
pride. Three times had he called for the boatswain without receiving
any reply, or causing that functionary to appear.
When the captain first came out of the cabin, his only thought
was to punish the sailor-boy for striking his son; but his anger now
took another course, and his desire to visit the boatswain’s
contumacy with a heavy penalty was so great, that he forgot entirely
the object for which he had first wished him. Relinquishing his hold
on Tom’s shoulder, the captain hailed his first officer in a quick, stern
voice,
“Mr. Hart, bring aft Mr. Wilson, the boatswain.”
“Ay, ay, sir,” responded the mate, as he started toward the
forecastle-scuttle to hunt up the delinquent. “Hillo, below there!” he
hailed, when he reached the scuttle, “You’re wanted on deck, Mr.
Wilson!”
“Who wants me?” was the reply that resounded, seemingly, from
one of the bunks close up the ship’s eyes.
“Captain Andrews is waiting for you on the quarter-deck; and if
you are not fond of tornadoes, you had better be in a hurry,”
answered the mate.
Notwithstanding the chief dickey’s hint, the boatswain seemed to
entertain no apprehensions about the reception he would meet at
the hands of the enraged skipper; for several minutes elapsed before
he made himself visible on deck.
As soon as the captain saw the boatswain, his anger increased,
and he became deadly pale from excess of passion. Waiting until
Wilson came within a few feet of him, he addressed him in that low,
husky voice, that more than any other proves the depth of a
person’s feeling, with,
“Why have you so long delayed obeying my summons, Mr.
Wilson?”
“I was asleep in the forecastle, sir, and came as soon as I heard
Mr. Hart call,” replied Wilson.
But the tone in which he spoke, the look of his eye, the
expression of his countenance, would at once have convinced a less
observant person than Captain Andrews, that the excuse offered was
one vamped up for the occasion, and not the real cause of the man’s
delay.
“Asleep, sir! Attend now to the duty I wish you to perform—and
be awake, sir, about it! And you may, perhaps, get off easier for your
own dereliction afterward—for your conduct shall not remain
unpunished,” answered the captain.
“Captain Andrews, boy and man, I have been going to sea now
these twenty-five years, and no one ever charged Bob Wilson with
not knowing or not doing his duty before, sir!” rejoined the
boatswain, evidently laboring under as much mental excitement as
the captain.
“None of your impertinence, sir! Not a word more, or I will learn
you a lesson of duty you ought to have been taught when a boy.
Where’s your cat,[2] sir?” continued the captain.
“In the razor-bag,”[3] replied the boatswain.
“Curse you!” ejaculated the captain, almost beside himself at this
reply, yet striving to maintain his self-possession; “one more insolent
word, and I will have you triced up. Strip that boy and make a
spread-eagle of him; then get your cat and give him forty.”
During this conversation between the captain and the boatswain,
the crew had been quietly gathering on the lee-side of the quarter-
deck, until at this juncture every seaman in the ship, except the man
at the wheel, was within twenty feet of the excited speakers. Not a
word had been spoken amongst them; but it was evident from the
determination imprinted upon their countenances, from their
attitudes, and from the extraordinary interest they took in the scene
then transpiring, that there was something more in the boatswain’s
insubordination than appeared on the surface; and whatever it was,
the crew were all under the influence of the same motive.
Mr. Wilson, the boatswain of the Josephine, was a first-rate and
thorough-bred seaman. No part of his duty was unfamiliar to him;
and never did he shrink from performing any portion of it on account
of danger or fatigue. Like many other simple-minded, honest-
hearted sons of Neptune, he troubled himself but little about
abstruse questions on morals; but he abhorred a liar, despised a
thief, and perfectly detested a tyrant. And though he could bear a
goodly quantity of tyrannical treatment himself, without heeding it, it
made his blood boil, and his hand clench, to see a helpless object
maltreated.
Ever since the Josephine had left port, there had been growing
amongst the crew a disposition to prevent their favorite, Tom, the
sailor-boy, from being imposed upon and punished, as he had been,
for no other reason than the willfulness of the captain’s son, and the
caprice of the captain’s wife. Not a man on board liked the spoiled
child of the cabin. No fancy, either, had they for his mother;
because, right or wrong, she always took her son’s part, and
oftentimes brought the sailors into trouble. The last time Tom had
been punished a grand consultation had been held in the forecastle,
at which the boatswain presided; and he, with the rest of the crew,
had solemnly pledged themselves not to let their little messmate be
whipped again unless, in their opinion, he deserved it.
This was the reason why the boatswain, one of the best men in
the ship, had skulked when he heard the captain’s call: he had seen
him come out of the cabin with Tom, and rightly anticipated the duty
he was expected to perform. Such great control does the habit of
obedience exercise over seamen, that although he was resolved to
die before he would suffer Tom to be whipped for nothing, much less
inflict the punishment himself, the boatswain felt a great
disinclination to have an open rupture with his commanding officer.
The peremptory order last issued by the captain, however, brought
affairs to a crisis there was no avoiding; he either had to fly in the
face of quarter-deck authority, or break his pledge to his messmates
and his conscience. This, Wilson could not think of doing; and
looking his captain straight in the face, in a quiet tone, and with a
civil manner, he thus addressed his superior:
“It does not become me, Captain Andrews, so be as how, for to
go, for to teach my betters—and—and—” here the worthy boatswain
broke down, in what he designed should be a speech, intended to
convince the captain of his error; but feeling unable to continue, he
ended abruptly, changing his voice and manner, with “Blast my eyes!
if you want the boy whipped, you can do it yourself.”
Hardly had the words escaped the speaker’s lips, before the
captain, snatching up an iron belaying-pin, rushed at the boatswain,
intending to knock him down; but Wilson nimbly leaped aside, and
the captain’s foot catching in a rope, he came down sprawling on the
deck. Instantly regaining his feet, he rushed toward the cabin, wild
with rage, for the purpose of obtaining his pistols. Several minutes
elapsed before he returned on deck; when he did he was much
more calm, although in each hand he held a cocked pistol.
The quarter deck he found bare; the crew, with little Tom in their
midst, having retired to the forecastle, where they were engaged in
earnest conversation. The second mate was at the wheel, the
seaman who had been at the helm having joined his comrades, so
that the only disposable force at the captain’s command was the
chief mate, the steward and himself, the cook being fastened up in
his galley by the seamen. On the forecastle were fifteen men. The
odds were great; but Captain Andrews did not pause to calculate
chances—his only thought was to punish the mutinous conduct of
his crew, never thinking of the possibility of failure.
Giving one of his pistols to Mr. Hart, and telling the steward to
take a capstan bar, the captain and his two assistants boldly
advanced to compel fifteen sailors to return to their duty.

[2] An instrument used for punishment.


[3] The technical name of the bag in which the cats are
kept.

——
CHAPTER III.
They were met, as the rock meets the wave,
And dashes its fury to air;
They were met, as the foe should be met by the brave,
With hearts for the conflict, but not for despair.

Whilst the captain, mate and steward, were making their brief
preparation for a most hazardous undertaking, the men of the
Josephine, with that promptness and resolution so common amongst
seamen when they think at all, had determined upon the course
they would adopt in the impending struggle.
Although the numerical discrepancy between the two parties
seemed so great, the actual difference in their relative strength was
not so considerable as it appeared. The sailors, it is true, had the
physical force—they were five to one; but the captain’s small band
felt more confidence from the moral influence that they knew was
on their side, than if their numbers had been trebled, without it.
Habit ever exercises a controlling influence, unless overcome by
some powerful exciting principle, and men never fly in the face of
authority to which they have always been accustomed to yield
implicit obedience, but from one of two causes—either a hasty
impulse, conceived in a moment, and abandoned by actors
frightened at their own audacity; or, a sense of wrong and injustice
so keen and poignant, as to make death preferable to further
submission.
Aware of custom’s nearly invincible power, having often seen
seamen rebel, and then at the first warning gladly skulk back to their
duty, the captain unhesitatingly advanced up the weather-gangway
to the break of the forecastle, and confronted his mutinous crew.
The men, who were huddled around the end of the windlass, some
sitting, others standing, talking together in low tones, only showed
they were aware of the captain’s presence by suddenly ceasing their
conversation—but not a man of them moved.
Captain Andrews, though quick tempered, was a man of
judgment and experience; and he saw by the calmness and
quietness of his men, that their insubordination was the result of
premeditation—a thing he had not before thought—and he became
aware of the difficulties of his position. He could not, for his life,
think of yielding; to give up to a sailor would, in his estimation, be
the deepest degradation. And moral influence was all he could rely
upon with which to compel obedience—feeling that if an actual strife
commenced, it could but result in his discomfiture. His tone,
therefore, was low and determined, as with cocked pistol in hand he
addressed his crew:
“Men, do you know that you are, every one of you, guilty of
mutiny? Do you know that the punishment for mutiny on the high
seas is death? Do you know this? Have you thought of it?” Here the
captain paused for an instant, as if waiting for a reply; and a voice
from the group around the windlass answered—
“We have!”
Rather surprised at the boldness of the reply, but still retaining
his presence of mind, the captain continued:
“What is it then that has induced you to brave this penalty? Have
you been maltreated? Do you not have plenty of provisions? Your
regular watches below? Step out, one of you, and state your
grievances. You know I am not a tyrant, and I wish from you nothing
more than you promised in the shipping articles!”
At this call, the eyes of the men were all turned toward Wilson,
the boatswain, who, seeing it was expected from him, stepped out
to act as spokesman. Respectfully touching his tarpaulin, he waited
for the captain to question him. Observing this, the captain said,
“Well, Wilson, your messmates have put you forth as their
speaker; and it strikes me that you are the ringleader of this
misguided movement. I am certain you have sense enough to
understand the risk you are running, and desire you to inform me
what great wrong it is that you complain of. For assuredly you must
feel grievously imposed upon, to make you all so far forget what is
due to yourselves as seamen, to me as your captain, and to the laws
of your country!”
“I ain’t much of a yarn-spinner, Captain Andrews, and I can turn
in the plies of a splice smoother and more ship-shape than the ends
of a speech; and it may be as how I’ll ruffle your temper more nor it
is now, by what I have to say—” commenced the boatswain.
“Never mind my temper, sir,” interrupted the captain, “proceed!”
“We all get plenty of grub, Captain Andrews, and that of the
best,” continued Wilson; his equanimity not in the least disturbed by
the skipper’s interruption. “We have our regular watches, and don’t
complain of our work, for we shipped as seamen, and can all do
seamen’s duty. But sailors have feelings, Captain Andrews, though
they are not often treated as if they had; and it hurts us worse to
see those worked double-tides who can’t take their own part, than if
we were mistreated ourselves; and to come to the short of it, all this
row’s about little Tom, there, and nothing else.”
“Is he not treated just as well as the rest of you? Has he not the
same quarters, and the same rations, that the men are content
with? Who works him double-tides?” answered the captain, his
anger evidently increasing at the mention of Tom’s name; and the
effort to restrain himself, being almost too great for the choleric
officer to compass.
“You can’t beat to wind’ard against a head-sea, Captain Andrews,
without a ship’s pitching, no more than you can reef a to’s-sail
without going aloft.” Wilson went on without change in manner,
though his voice became more concise and firm in its tone. “And I
can’t tell you, like some of them shore chaps, what you don’t want
to hear, without heaving you aback. We ain’t got any thing agin you,
if you was let alone; all we wants is for you to give your own orders,
and to keep Mrs. Andrews from bedeviling Tom. The boy’s as good a
boy as ever furled a royal, and never skulks below when he’s wanted
on deck; but he stands his regular watches, and then, when he
ought to sleep, he’s everlastingly kept in the cabin, and whipped and
knocked about for the amusement of young master, and that’s just
the whole of it. We’ve stood it long enough, and wont return to duty
until you promise—”
“Silence, sir!” roared the captain, perfectly furious, and unable
longer to remain quiet. “Not another word! I’ve listened to insolence
too long by half, already! Now, sir, I have a word to say to you, and
mind you heed it. Walk aft to the quarter-deck!”
The boatswain, though he heard the order plainly, and
understood it clearly, paid no attention to it.
“Do you hear me, sir?” asked the captain. “I give you whilst I
count ten, to start. I do not wish to shoot you, Wilson; but if you do
not move before I count ten, I’ll drive this ball through you—as I
hope to reach port, I will!”
Raising his pistol until it covered the boatswain’s breast, the
captain commenced counting in a clear and audible tone. Intense
excitement was depicted on the faces of the men; and some anxiety
was shown by the quick glances cast by the chief mate and steward,
first at the captain, and then at the crew. Wilson, with his eyes fixed
in the captain’s face, and his arms loosely folded across his breast,
stood perfectly quiet, as if he were an indifferent spectator.
“Eight! Nine!” said the captain, “there is but one left, Wilson; with
it I fire if you do not start.”
The boatswain remained motionless. “Te—” escaped the
commander’s lips; and as it did, the sharp edge of Wilson’s heavy
tarpaulin hat struck him a severe blow in the face. This was so
entirely unexpected, that the captain involuntarily threw back his
head, and by the same motion, without intending it, threw up his
arm and clenched his hand enough to fire off the pistol held in it;
the ball from which went through the flying-jib, full twenty feet
above Wilson’s head.
The charm that had held the men in check, was broken by the
first movement toward action, and they made a rush toward the
captain and his two supporters. Bravely, though, they stood their
ground; and Frank Adams, the sailor introduced with Tom in the
forecastle, received the ball from the mate’s pistol in the fleshy part
of his shoulder, as he was about to strike that worthy with a
handspike. Gallantly assisted by the steward, the captain and mate
made as much resistance as three men could against fifteen. The
odds were, however, too great; spite of their bravery, the three were
soon overpowered and the contest was nearly ended, when a
temporary change was made in favor of the weaker party by the
appearance in the fray of the second mate. He, during the whole
colloquy, had been at the wheel, forgotten by both parties. His
sudden arrival, therefore, as with lusty blows he laid about him,
astonished the seamen, who gave back for an instant, and allowed
their opponents to regain their feet. They did not allow them much
time, however, to profit by this respite, for in a few seconds,
understanding the source from whence assistance had come, they
renewed the attack with increased vigor, and soon again obtained
the mastery. But it was no easy matter to confine the three officers
and the steward, who resisted with their every power, particularly as
the men were anxious to do them no more bodily injury than they
were compelled to, in effecting their purpose.
So absorbed were all hands in the strife in which they were
engaged, that not one of them noticed the fact that what had been
the weather-side of the barque at the commencement of the affray,
was now the lee; nor did any of the men—all seamen as they were—
observe that the vessel was heeling over tremendously, her lee-
scuppers nearly level with the water. A report, loud as a cannon,
high in the air, first startled the combatants; then, with a rushing
sound, three large, heavy bodies, fell from aloft, one of which
striking the deck near the combatants, threatened all with instant
destruction, whilst the other two fell with a loud splash into the sea
to leeward.
In the new danger, both the victors and vanquished were equally
interested, and at the same instant looked aloft to discover the
cause. The first glance convinced every one of the necessity for
prompt and vigorous action. Their position was, indeed, one fraught
with imminent danger. Left without a helmsman, by the second mate
going to the assistance of the captain, the barque, close-hauled with
a stiff breeze blowing, had come up in the wind, and was now flat
aback; that is, the wind, instead of blowing against the sails from
behind, was before them. The fore and main-royal, and top-gallant
masts, with all their gear, had been carried away; and the ship was
gathering stern-way at a rate that would soon run her under.
The natural desire for self-preservation, combined with the
instincts and habits of both officers and men to cause them entirely
to forget the fierce contest in which they had just been engaged—
their thoughts were changed from each other, to the ship and its
situation—and the officers were at once permitted to regain their
feet.
No sooner did Captain Andrews find himself at liberty, than he at
once assumed command, and issued his orders as loud and clear as
if nothing had interrupted his authority.
“To the wheel! to the wheel! Mr. Hart! All hands ware ship!” were
his first words; and the men with alacrity hurried to their stations,
whilst the mate ran to the helm.
The captain’s wife and son had been in the cabin, anxiously
awaiting the result of the controversy on the forecastle, but alarmed
by the failing spars, they had hurried on deck and were now on the
poop. In the hurry and confusion consequent upon the ship’s
hazardous position, all hands were so busy that no one paid
attention to Charles and Mrs. Andrews; and they were too much
alarmed to take due care of themselves, else would they have
sought a less exposed situation. As the spanker jibed, Charles was
standing nearly amidships on the deck, and before he even had time
to shriek, the boom struck him and hurled him over the monkey-rail
into the sea. His mother, who was close to the mizzen-mast, saw
him just as he went over, and terror-stricken, sunk to the deck in a
swoon, without uttering a sound. Unable to swim, a puny child in the
angry waves of the rough Atlantic, the case of Charles seemed a
hopeless one; but rescue came from a source he could have least
expected. Tom, the sailor-boy, who was on the tafferel belaying the
spanker-sheet to windward, recognized the captain’s son as he
floated clear of the stern; and actuated by that generous, gallant
spirit that had so endeared him to his messmates, he shouted to the
mate that Charles was over-board! and fearlessly sprang into the sea
to his assistance. Tom was an excellent swimmer, and he found no
difficulty in supporting Charles’ delicate form until the barque hove
round, when they were both picked up and taken on board.
The joy of the mother at having restored to her the idol of her
heart; the grateful feelings she and the father felt toward the
deliverer of their child, we will not attempt to describe; only the
results will we give of this heroic action. Tom was treated by the
captain as a son; the crew were forgiven for their mutinous conduct,
and cheerfully returned to duty; and Tom, now a distinguished naval
officer, dates his first step upon the ladder that leads to eminence,
from the day he so narrowly escaped a severe whipping.
Laurensville, South Carolina.

THE LADY OF CASTLE WINDECK.


(FROM THE GERMAN OF CHAMISSO.)

———
BY WILLIAM CULLEN BRYANT.
———
Rein in thy snorting charger!
That stag but cheats thy sight;
He is luring thee on to Windeck,
With his seeming fear and flight.

Now, where the mouldering turrets


Of the outer gate arise,
The knight gazed over the ruins
Where the stag was lost to his eyes.

The sun shone hot above him;


The castle was still as death;
He wiped the sweat from his forehead,
With a deep and weary breath.

“Who now will bring me a beaker


Of the rich old wine that here,
In the choked up vaults of Windeck,
Has lain for many a year?”

The careless words had scarcely


Time from his lips to fall,
When the Lady of Castle Windeck
Come round the ivy-wall.

He saw the glorious maiden


In her snow-white drapery stand,
The bunch of keys at her girdle,
The beaker high in her hand.

He quaffed that rich old vintage;


With an eager lip he quaffed;
But he took into his bosom
A fire with the grateful draught.

Her eyes unfathomed brightness!


The flowing gold of her hair!
He folded his hands in homage,
And murmured a lover’s prayer.

She gave him a look of pity,


A gentle look of pain;
And quickly as he had seen her
She passed from his sight again.

And ever, from that moment,


He haunted the ruins there,
A sleepless, restless wanderer,
A watcher with despair.

Ghost-like and pale he wandered,


With a dreamy, haggard eye;
He seemed not one of the living,
And yet he could not die.

’Tis said that the lady met him,


When many years had past,
And kissing his lips, released him
From the burden of life at last.

THE YOUNG MOTHER’S LAMENT.


———
BY MRS. E. C. KINNEY.
———
Oh, what is all this world to me,
Now that my babe is gone—
From every thing I hear, or see,
The light of life has flown!

It is not summer to my eyes,


For summer’s sun is hid—
He, who made fair the earth and skies,
Sleeps ’neath a coffin-lid.

There is no verdure to be seen—


No flowers upon the lea;
For he, whose smile made all things green,
Hath no more smiles for me.

Now all things wear the sickly-hue


Of my own spirit sad,
And nothing can that charm renew
Which made the earth look glad.

Oh, he was such a lovely boy—


So innocent, so fair;
His every look so full of joy—
Such sunlight in his hair!

That when he nestled to my breast,


And looked up lovingly,
I thought no mother half so blest
In all the world as I.

But now, alas! since he has died,


All day and night I pine,
And never was a heart beside
So desolate as mine.

Here are the toys his little hands


So sportively did use,
And here his empty cradle stands,
And here his tiny shoes:

Oh, take them, take them from my sight!


Each sends a cruel dart—
Sharpened by fatal memories bright—
Into my bleeding heart.

Take all away, since he is gone—


Save one of his fair curls,
And that shall on my breast be worn,
Set round with costly pearls.

But, like the diamond glistening bright


Upon a withered wreath,
’Twill make more dreary by its light
The wasted heart beneath.
Jenny Lind
(IN LA SONNAMBULA)
Engraved in London for Graham’s Magazine by W. H. Mote after the
original Painting by J. W. Wright

JENNY LIND.
———
BY HENRY T. TUCKERMAN.
———

[WITH A PORTRAIT.]

Sure something holy lodges in that breast,


And with mere rapture moves the vocal air,
To testify its hidden residence.
How sweetly did they float upon the wings
Of Silence, through the empty-vaulted night,
At every fall smoothing the raven down
Of darkness till it smiled. Comus.

The Life of the North is to us a fresh revelation; and, by a striking


coincidence, one after another of its phases have come upon our
transatlantic vision, in rapid succession. To many Americans
Thorwaldsen was the only name associated with art, but a few years
since; and to those who had visited Rome, the benign and venerable
man was a vivid and pleasing reminiscence, appropriate to the idea
of his grand apostolic figures, and the affectionate honor in which
his native Denmark held their noble sculptor. But with Ole Bull fairly
commenced our knowledge of the genius of Northern Europe. The
play of the wind through her forests of pines, the glint of her frozen
streams, the tenderness of her households, and the solemnity of her
faith, seemed to breathe in the wizard tones of his violin; while her
integrity was written in the form, the manners, and the very smile of
the musician. Then the spirit of her literature began slowly to win its
gentle but impressive way to the American heart. Longfellow’s
translation of Bishof’s Tegnér’s Children of the Lord’s Supper, with
the graphic introduction descriptive of moral life in Sweden, touched
the same chord in New England breasts, that had vibrated to the
religious pathos of Bryant, Dana, and Hawthorne; while not a few
readers became simultaneously aware of a brave Danish poet
recently followed to the tomb by the people of Copenhagen, with
every token of national grief. The dramas of Œhlenschläger, from
their union of familiar expression with the richest feeling, though but
partially known in this country, awakened both curiosity and interest.
Then, too, came to us the domestic novels of Miss Bremer,
portraying so heartily the life of home in Sweden, and appealing to
the most universal sympathies of our people. Finally, Hans
Andersen’s delicious story-books veiling such fine imaginative powers
under the guise of the utmost simplicity, raised up for him scores of
juvenile admirers, while children of a larger growth enjoyed the
originality of his fictions with equal zest, as the offspring of rare
human sympathy and original invention. The pictures wafted to our
shores by the late revolutionary exigencies of the Continent, have
often yielded glimpses of northern scenery. Norwegian forests, skies
and mountains, attracted the eye at the Dusseldorf gallery; and thus
through both art and literature, the simple, earnest, and poetic
features of life in the north, were brought within the range of our
consciousness. It developed unimagined affinities with our own; and
now, as it were, to complete and consecrate the revelation, we are
to hear the vocal genius of Northern Europe—the Swedish
nightingale, Jenny Lind, is coming!
From an unpretending edifice in one of the by-streets of the city
of Stockholm in Sweden, a quarter of a century ago, a troop of
children might have been seen to emerge, at noon, and break the
silence that at other hours invested the place, with the lively chat
and quick laughter natural to emancipated scholars. In a few
moments they dispersed to their several homes, and early the next
day were again visible, one by one, disappearing, with a more
subdued bearing, within the portal of the humble domicil.
Stockholm is justly regarded as the most elegant city of Northern
Europe. It is situated at the junction of the lake Mälar with an inlet
of the Baltic. Although usually described as founded on seven isles,
it is, in point of fact, mainly situated on three; the smallest and most
central having been the original site, and still constituting the most
populous and active section. The irregularity of its form, and the
blending of land and water, renders the appearance of the city
remarkably picturesque. From the elevated points, besides the
various buildings, craft of all kinds in motion and at anchor,
numerous bridges and a fine back-ground of mountains are
discernible, and combine to form a beautiful panorama. The royal
palace is exceeded in magnificence only by that of Versailles.
Through this busy and varied scene, on a pleasant day, there moved
rapidly the carriage of one of those useful, though unrecognized
beings, who seem born to appreciate the gifts which God so liberally
dispenses, but whom the insensibility and selfishness of mankind, in
general, permit to languish in obscurity until a fortunate
circumstance brings them to light. Some time previous, the good
lady, in passing the seminary to which we have alluded, had been
struck with the beauty of a child’s voice that rose blithely from the
dwelling. She was induced to alight and enter; and her astonishment
was only increased upon discovering that this cheerful song came
from a diminutive girl, busied in arranging the school-room, during a
temporary recess. She learned that this maiden was the daughter of
the school-mistress; and the somewhat restricted air of homely
comfort visible in the establishment, and the tinge of severity in the
manners of the mother, contrasted forcibly in the lady’s imagination
with the apparently instinctive soaring of the child’s spirit into the
atmosphere of song, from her dim and formal surroundings, as the
sky-lark lifts itself from a lowly nest among the dark weeds up to the
crystal heavens. It was a sweet illustration of the law of
compensation.
The air the child was singing, as she busied herself about the
room, was a simple, native strain, quite familiar and by no means
difficult of execution; it was the quality of the voice, the natural flow
of the notes, the apparent ease, grace and earnest sweetness of the
little songstress, that gained the visiter’s ear and heart; and now she
had come to urge upon the parents the duty of affording every
encouragement to develop a gift so rare and beautiful; she
expressed her conviction that the child was born for a musical artist,
and destined not only to redeem her parents from want, but to do
honor to her country. This impression was deepened when she
learned that this musical tendency manifested itself as early as the
age of three, and that the little girl had long awakened the wonder
of the family by repeating accurately even intricate airs, after having
heard them but once; that she had thus sung habitually,
spontaneously, and seemed to find of her own volition, a peculiar
consolation in the act for the dry routine of her life, though from
without, not a single circumstance gave any impulse or direction to
this vocal endowment.
She exhibited also to the just perception of Madame Lundberg,
herself a celebrated Swedish actress, as well as a benevolent
woman, the usual conditions of genius, in backward physical growth,
precocious mental vigor, and mature sensibilities. The latter, indeed,
were so active, that her mother, and even her kind adviser doubted
if she possessed sufficient energy of character for so trying a
profession as that of an artist; and this consideration added to the
prejudice of the parents against a public, and especially a theatrical
career, for a time, chilled the hopes of the enthusiastic patroness. At
length, however, their consent was obtained that the experiment
should be tried, and the diffident little girl, only accustomed to
domestic privacy, but with a new and strange hope wildly fluttering
in her bosom, was taken to Croelius—a veteran music-master of
Stockholm; who was so delighted with her rare promise that one day
he led her to the house of Count Pucke, then director of the court
theatre. Her reception, however, did not correspond with the old
man’s desires; for the nobleman coldly inquired what he was
expected to do with such a child? It must be confessed that the
absence of beauty and size did not, at the first glance, create any
high anticipations in behalf of the demure maiden. Croelius, though
disappointed, was quite undismayed; he entreated the director to
hear her sing, and declared his purpose to teach her gratuitously, if
he could in no other way secure the cultivation of her voice and
talents. This earnestness induced the count to listen with attention
and candor; and the instant she had finished, he exclaimed, “She
shall have all the advantages of the Stockholm Academy!” Such was
Jenny Lind’s initiation into the life of an artist.
She now began regularly to appear on the stage, and was soon
an adept in juvenile parts. She proved widely attractive in
vaudevilles, which were written expressly for her; and it is
remarkable that the charm did not lie so much in the precocious
intelligence, as in the singular geniality of the little actress. Nature
thus early asserted her dominion. There was an indefinable human
interest, a certain original vein that universally surprised and
fascinated, while it took from the child the eclat of a mere infant
phenomenon, by bringing her from the domain of vulgar wonder into
the range of that refined sympathy one touch of which “makes the
whole world kin.” In a year Croelius reluctantly gave up his pupil to
Berg, who to kindred zeal united far more energy; and by him she
was inducted thoroughly into the elements of her art.
Probation is quite as essential to the true development of art as
encouragement. The eager, impassioned, excitable temperament
needs to be chastened, the recklessness of self-confidence awed,
and that sublime patience induced through which reliable and
tranquil energy takes the place of casual and unsustained activity. By
nature Jenny Lind was thoughtful and earnest, disposed to silence,
and instinctively reserved; while the influence of her early home was
to subdue far more than to exhilarate. The change in her mode of
life and prospects was so unexpected, her success as a juvenile
prodigy so brilliant, and the universal social favor she enjoyed, on
account of the winsome amiability of her character, so fitted to elate
a youthful heart, that we cannot but regard it as one of the many
providential events of her career, that just at the critical moment
when the child was losing herself in the maiden, and nature and
education were ultimately shaping her artistic powers, an
unexpected impediment was allowed to check her already too rapid
advancement; and a pause, sad enough at the time, but fraught
with enduring benefit, gave her occasion to discipline and elevate
her soul, renew her overtasked energies, and plume her wings while
thus aware of the utility of her trial, we can easily imagine its
bitterness. The loss of a gift of nature through which a human being
has learned to find both the solace and the inspiration of existence,
upon which the dearest hopes were founded, and by which the most
glorious triumphs were achieved, is one of those griefs few can
realize. Raphael’s gentle heart bled when feebleness unnerved the
hand that guided the pencil to such lovely issues, and big tears
rolled down Scott’s manly cheek when he strove in vain to go on
with his latest composition. How desolate then must that young
aspirant for the honor, and the delights of the vocal art, have felt
when suddenly deprived of her voice! The dream of her youth was
broken in a moment. The charm of her being faded like a mist; and
the star of hope that had thus far beamed serenely on her path,
grew dim in the cold twilight of disappointment—keen, entire and
apparently irremediable. This painful condition was aggravated by
the fact that her age now rendered it out of the question to perform
childish parts, while it did not authorize those of a mature character.
The circumstances, too, of her failure were singularly trying. She
was announced to appear as Agatha in Weber’s Frieschutz—a
character she had long regarded as that in which her ability would
be genially tested. To it her young ambition had long pointed, and
with it her artistic sympathies were familiarly identified. The hour
came, and that wonderful and delicate instrument—that as a child
she had governed so adroitly, that it seemed the echo of her mind;—
that subtle medium through which her feelings had been wont to
find such ready and full vent, refused to obey her will, yielded not to
the pleadings of love or ambition; was hushed as by some cruel
magic—and Jenny Lind was mute, with anguish in her bosom; her
friends looking on in tearful regret, and her maestro chagrined
beyond description! Where had those silvery tones fled? What
catastrophe had all at once loosened those invisible harp strings?
The splendid vision of fame, of bounteous pleasure, of world-excited
sympathy, and of triumphant art, disappeared like the gorgeous
cities seen by the traveler, from the Straits of Messina, painted in
tinted vapor on the horizon. Jenny Lind ceased to sing, but her love

You might also like