100% found this document useful (14 votes)
749 views

Download ebooks file Essential Algorithms a Practical Approach to Computer Algorithms 1st Edition Rod Stephens all chapters

Rod

Uploaded by

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

Download ebooks file Essential Algorithms a Practical Approach to Computer Algorithms 1st Edition Rod Stephens all chapters

Rod

Uploaded by

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

Download the full version of the ebook at ebookname.

com

Essential Algorithms a Practical Approach to


Computer Algorithms 1st Edition Rod Stephens

https://ebookname.com/product/essential-algorithms-a-
practical-approach-to-computer-algorithms-1st-edition-rod-
stephens/

OR CLICK BUTTON

DOWNLOAD EBOOK

Download more ebook instantly today at https://ebookname.com


Instant digital products (PDF, ePub, MOBI) available
Download now and explore formats that suit you...

Essential Algorithms A Practical Approach to Computer


Algorithms 1st Edition Rod Stephens

https://ebookname.com/product/essential-algorithms-a-practical-
approach-to-computer-algorithms-1st-edition-rod-stephens-2/

ebookname.com

Essential Algorithms A Practical Approach to Computer


Algorithms Using Python and C Second Edition Rod Stephens

https://ebookname.com/product/essential-algorithms-a-practical-
approach-to-computer-algorithms-using-python-and-c-second-edition-rod-
stephens/
ebookname.com

Algorithms in C Computer Science Series 1st Edition


Sedgewick

https://ebookname.com/product/algorithms-in-c-computer-science-
series-1st-edition-sedgewick/

ebookname.com

Linguistics An Introduction 2nd Edition Andrew Radford

https://ebookname.com/product/linguistics-an-introduction-2nd-edition-
andrew-radford/

ebookname.com
Current Issues in Theoretical Philosophy Volume 1 What is
Truth

https://ebookname.com/product/current-issues-in-theoretical-
philosophy-volume-1-what-is-truth/

ebookname.com

Qualities of Effective Teachers 3rd Edition James H.


Stronge

https://ebookname.com/product/qualities-of-effective-teachers-3rd-
edition-james-h-stronge/

ebookname.com

Geriatrics Health and Medical Issues Today 1st Edition


Carol Leth Stone

https://ebookname.com/product/geriatrics-health-and-medical-issues-
today-1st-edition-carol-leth-stone/

ebookname.com

The Last Enemy 1st Edition Michael Eugene Wittmer

https://ebookname.com/product/the-last-enemy-1st-edition-michael-
eugene-wittmer/

ebookname.com

Making New Words Morphological Derivation in English R. M.


W Dixon

https://ebookname.com/product/making-new-words-morphological-
derivation-in-english-r-m-w-dixon/

ebookname.com
Stroke What Do I Do Now 2nd Edition Edition Louis R.
Caplan

https://ebookname.com/product/stroke-what-do-i-do-now-2nd-edition-
edition-louis-r-caplan/

ebookname.com
bindex.indd 05:47:54:PM 07/10/2013 Page 602
Essential Algorithms
A Practical Approach to Computer
Algorithms

Rod Stephens

ffirs.indd 05:53:16:PM 07/10/2013 Page i


Essential Algorithms: A Practical Approach to Computer Algorithms

Published by
John Wiley & Sons, Inc.
10475 Crosspoint Boulevard
Indianapolis, IN 46256
www.wiley.com
Copyright © 2013 by John Wiley & Sons, Inc., Indianapolis, Indiana
Published simultaneously in Canada

ISBN: 978-1-118-61210-1
ISBN: 978-1-118-61276-7 (ebk)
ISBN: 978-1-118-79729-7 (ebk)

Manufactured in the United States of America

10 9 8 7 6 5 4 3 2 1

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, scanning or otherwise, except as permitted
under Sections 107 or 108 of the 1976 United States Copyright Act, without either the prior written permis-
sion of the Publisher, or authorization through payment of the appropriate per-copy fee to the Copyright
Clearance Center, 222 Rosewood Drive, Danvers, MA 01923, (978) 750-8400, fax (978) 646-8600. Requests to the
Publisher for permission should be addressed to the Permissions Department, John Wiley & Sons, Inc., 111
River Street, Hoboken, NJ 07030, (201) 748-6011, fax (201) 748-6008, or online at http://www.wiley.
com/go/permissions.
Limit of Liability/Disclaimer of Warranty: The publisher and the author make no representations or war-
ranties with respect to the accuracy or completeness of the contents of this work and specifically disclaim all
warranties, including without limitation warranties of fitness for a particular purpose. No warranty may be
created or extended by sales or promotional materials. The advice and strategies contained herein may not
be suitable for every situation. This work is sold with the understanding that the publisher is not engaged in
rendering legal, accounting, or other professional services. If professional assistance is required, the services
of a competent professional person should be sought. Neither the publisher nor the author shall be liable for
damages arising herefrom. The fact that an organization or Web site is referred to in this work as a citation
and/or a potential source of further information does not mean that the author or the publisher endorses
the information the organization or website may provide or recommendations it may make. Further, readers
should be aware that Internet websites listed in this work may have changed or disappeared between when
this work was written and when it is read.

For general information on our other products and services please contact our Customer Care Department
within the United States at (877) 762-2974, outside the United States at (317) 572-3993 or fax (317) 572-4002.

Wiley publishes in a variety of print and electronic formats and by print-on-demand. Some material included
with standard print versions of this book may not be included in e-books or in print-on-demand. If this book
refers to media such as a CD or DVD that is not included in the version you purchased, you may download
this material at http://booksupport.wiley.com. For more information about Wiley products,
visit www.wiley.com.

Library of Congress Control Number: 2013941603

Trademarks: Wiley and the Wiley logo are trademarks or registered trademarks of John Wiley & Sons, Inc.
and/or its affiliates, in the United States and other countries, and may not be used without written permission.
All other trademarks are the property of their respective owners. John Wiley & Sons, Inc. is not associated
with any product or vendor mentioned in this book.

ffirs.indd 05:53:16:PM 07/10/2013 Page ii


About the Author

Rod Stephens started out as a mathematician, but while studying at MIT, he


discovered how much fun algorithms are. He took every algorithms course MIT
offered and has been writing complex algorithms ever since.
During his career, Rod has worked on an eclectic assortment of applications
in such fields as telephone switching, billing, repair dispatching, tax process-
ing, wastewater treatment, concert ticket sales, cartography, and training for
professional football players.
Rod is a Microsoft Visual Basic Most Valuable Professional (MVP) and has
taught introductory programming at ITT Technical Institute. He has written
more than 2 dozen books that have been translated into languages from all over
the world. He has also written more than 250 magazine articles covering C#,
Visual Basic, Visual Basic for Applications, Delphi, and Java.
Rod’s popular VB Helper website (www.vb-helper.com) receives several mil-
lion hits per month and contains tips, tricks, and example programs for Visual
Basic programmers. His C# Helper website (www.csharphelper.com) contains
similar material for C# programmers.
You can contact Rod at RodStephens@vb-helper.com or
RodStephens@csharphelper.com.

iii

ffirs.indd 05:53:16:PM 07/10/2013 Page iii


Credits

Executive Editor Business Manager


Robert Elliott Amy Knies
Project Editor Production Manager
Tom Dinse Tim Tate
Technical Editors Vice President and Executive
David Coleman Group Publisher
Jack Jianxiu Hao Richard Swadley
George Kocur
Vice President and Executive
Production Editor Publisher
Daniel Scribner Neil Edde
Copy Editor Associate Publisher
Gayle Johnson Jim Minatel
Editorial Manager Project Coordinator, Cover
Mary Beth Wakefield Katie Crocker
Freelancer Editorial Manager Proofreader
Rosemarie Graham Josh Chase, Word One
Associate Director of Marketing Indexer
David Mayhew Robert Swanson
Marketing Manager Cover Designer
Ashley Zurcher Ryan Sneed

iv

ffirs.indd 05:53:16:PM 07/10/2013 Page iv


Acknowledgments

Thanks to Bob Elliott, Tom Dinse, Gayle Johnson, and Daniel Scribner for all
of their hard work in making this book possible. Thanks also to technical edi-
tors George Kocur, Dave Colman, and Jack Jianxiu Hao for helping ensure the
information in this book is as accurate as possible. (Any remaining mistakes
are mine not theirs.)

ffirs.indd 05:53:16:PM 07/10/2013 Page v


Contents at a Glance

Introduction xv

Chapter 1 Algorithm Basics 1


Chapter 2 Numerical Algorithms 25
Chapter 3 Linked Lists 55
Chapter 4 Arrays 83
Chapter 5 Stacks and Queues 111
Chapter 6 Sorting 131
Chapter 7 Searching 163
Chapter 8 Hash Tables 169
Chapter 9 Recursion 185
Chapter 10 Trees 227
Chapter 11 Balanced Trees 277
Chapter 12 Decision Trees 297
Chapter 13 Basic Network Algorithms 325
Chapter 14 More Network Algorithms 355
Chapter 15 String Algorithms 377
Chapter 16 Cryptography 397
Chapter 17 Complexity Theory 419
Chapter 18 Distributed Algorithms 435
Chapter 19 Interview Puzzles 465
Appendix A Summary of Algorithmic Concepts 477
Appendix B Solutions to Exercises 487

Glossary 559
Index 573

vi

ffirs.indd 05:53:16:PM 07/10/2013 Page vi


Contents

Introduction xv
Chapter 1 Algorithm Basics 1
Approach 2
Algorithms and Data Structures 3
Pseudocode 3
Algorithm Features 6
Big O Notation 7
Common Runtime Functions 11
Visualizing Functions 17
Practical Considerations 17
Summary 19
Exercises 20
Chapter 2 Numerical Algorithms 25
Randomizing Data 25
Generating Random Values 25
Randomizing Arrays 31
Generating Nonuniform Distributions 33
Finding Greatest Common Divisors 33
Performing Exponentiation 35
Working with Prime Numbers 36
Finding Prime Factors 37
Finding Primes 39
Testing for Primality 40
Performing Numerical Integration 42
The Rectangle Rule 42
The Trapezoid Rule 43

vii

ftoc.indd 05:53:41:PM 07/10/2013 Page vii


viii Contents

Adaptive Quadrature 44
Monte Carlo Integration 48
Finding Zeros 49
Summary 51
Exercises 52
Chapter 3 Linked Lists 55
Basic Concepts 55
Singly Linked Lists 56
Iterating Over the List 57
Finding Cells 57
Using Sentinels 58
Adding Cells at the Beginning 59
Adding Cells at the End 60
Inserting Cells After Other Cells 61
Deleting Cells 62
Doubly Linked Lists 63
Sorted Linked Lists 65
Linked-List Algorithms 66
Copying Lists 67
Sorting with Insertionsort 68
Linked List Selectionsort 69
Multithreaded Linked Lists 70
Linked Lists with Loops 71
Marking Cells 72
Using Hash Tables 74
List Retracing 75
List Reversal 76
Tortoise and Hare 78
Loops in Doubly Linked Lists 80
Summary 81
Exercises 81
Chapter 4 Arrays 83
Basic Concepts 83
One-dimensional Arrays 86
Finding Items 86
Finding Minimum, Maximum, and Average 86
Inserting Items 88
Removing Items 89
Nonzero Lower Bounds 89
Two Dimensions 90
Higher Dimensions 91
Triangular Arrays 94
Sparse Arrays 97

ftoc.indd 05:53:41:PM 07/10/2013 Page viii


Contents ix

Find a Row or Column 100


Get a Value 101
Set a Value 101
Delete a Value 104
Matrices 105
Summary 108
Exercises 108
Chapter 5 Stacks and Queues 111
Stacks 111
Linked-List Stacks 112
Array Stacks 113
Double Stacks 115
Stack Algorithms 117
Queues 123
Linked-List Queues 123
Array Queues 124
Specialized Queues 127
Summary 128
Exercises 128
Chapter 6 Sorting 131
O(N2) Algorithms 132
Insertionsort in Arrays 132
Selectionsort in Arrays 134
Bubblesort 135
O(N log N) Algorithms 138
Heapsort 139
Quicksort 145
Mergesort 153
Sub O(N log N) Algorithms 156
Countingsort 156
Bucketsort 157
Summary 159
Exercises 160
Chapter 7 Searching 163
Linear Search 164
Binary Search 165
Interpolation Search 166
Summary 167
Exercises 168
Chapter 8 Hash Tables 169
Hash Table Fundamentals 170
Chaining 171

ftoc.indd 05:53:41:PM 07/10/2013 Page ix


x Contents

Open Addressing 172


Removing Items 174
Liner Probing 174
Quadratic Probing 176
Pseudorandom Probing 178
Double Hashing 178
Ordered Hashing 179
Summary 181
Exercises 182
Chapter 9 Recursion 185
Basic Algorithms 186
Factorial 186
Fibonacci Numbers 188
Tower of Hanoi 189
Graphical Algorithms 193
Koch Curves 193
Hilbert Curve 196
Sierpiń ski Curve 197
Gaskets 200
Backtracking Algorithms 201
Eight Queens Problem 203
Knight’s Tour 206
Selections and Permutations 209
Selections with Loops 210
Selections with Duplicates 211
Selections Without Duplicates 213
Permutations with Duplicates 214
Permutations Without Duplicates 215
Recursion Removal 216
Tail Recursion Removal 216
Storing Intermediate Values 218
General Recursion Removal 220
Summary 222
Exercises 223
Chapter 10 Trees 227
Tree Terminology 227
Binary Tree Properties 231
Tree Representations 234
Building Trees in General 234
Building Complete Trees 236
Tree Traversal 237
Preorder Traversal 238
Inorder Traversal 240
Postorder Traversal 242

ftoc.indd 05:53:41:PM 07/10/2013 Page x


Contents xi

Depth-first Traversal 243


Traversal Run Times 244
Sorted Trees 245
Adding Nodes 245
Finding Nodes 247
Deleting Nodes 248
Threaded Trees 250
Building Threaded Trees 251
Using Threaded Trees 254
Specialized Tree Algorithms 256
The Animal Game 256
Expression Evaluation 258
Quadtrees 260
Tries 266
Summary 270
Exercises 271
Chapter 11 Balanced Trees 277
AVL Trees 278
Adding Values 278
Deleting Values 281
2-3 Trees 282
Adding Values 283
Deleting Values 284
B-Trees 287
Adding Values 288
Deleting Values 289
Balanced Tree Variations 291
Top-down B-trees 291
B+trees 291
Summary 293
Exercises 293
Chapter 12 Decision Trees 297
Searching Game Trees 298
Minimax 298
Initial Moves and Responses 302
Game Tree Heuristics 303
Searching General Decision Trees 305
Optimization Problems 306
Exhaustive Search 307
Branch and Bound 309
Decision Tree Heuristics 310
Other Decision Tree Problems 316
Summary 322
Exercises 322

ftoc.indd 05:53:41:PM 07/10/2013 Page xi


xii Contents

Chapter 13 Basic Network Algorithms 325


Network Terminology 325
Network Representations 328
Traversals 331
Depth-first Traversal 331
Breadth-first Traversal 334
Connectivity Testing 335
Spanning Trees 337
Minimal Spanning Trees 338
Finding Paths 339
Finding Any Path 339
Label-Setting Shortest Paths 340
Label-Correcting Shortest Paths 344
All-Pairs Shortest Paths 345
Summary 350
Exercises 351
Chapter 14 More Network Algorithms 355
Topological Sorting 355
Cycle Detection 359
Map Coloring 359
Two-coloring 360
Three-coloring 362
Four-coloring 362
Five-coloring 363
Other Map-coloring Algorithms 367
Maximal Flow 368
Work Assignment 370
Minimal Flow Cut 372
Summary 374
Exercises 375
Chapter 15 String Algorithms 377
Matching Parentheses 378
Evaluating Arithmetic Expressions 379
Building Parse Trees 380
Pattern Matching 381
DFAs 381
Building DFAs for Regular Expressions 383
NFAs 386
String Searching 387
Calculating Edit Distance 391
Summary 394
Exercises 394
Chapter 16 Cryptography 397
Terminology 398
Transposition Ciphers 399

ftoc.indd 05:53:41:PM 07/10/2013 Page xii


Contents xiii

Row/column Transposition 399


Column Transposition 401
Route Ciphers 403
Substitution Ciphers 404
Caesar Substitution 404
Vigenère Cipher 405
Simple Substitution 407
One-Time Pads 408
Block Ciphers 408
Substitution-Permutation Networks 409
Feistel Ciphers 410
Public-Key Encryption and RSA 412
Euler’s Totient Function 413
Multiplicative Inverses 413
An RSA Example 414
Practical Considerations 414
Other Uses for Cryptography 415
Summary 416
Exercises 417
Chapter 17 Complexity Theory 419
Notation 420
Complexity Classes 421
Reductions 424
3SAT 425
Bipartite Matching 426
NP-Hardness 426
Detection, Reporting, and Optimization Problems 427
Detection ≤p Reporting 427
Reporting ≤p Optimization 428
Reporting ≤p Detection 428
Optimization ≤p Reporting 429
NP-Complete Problems 429
Summary 431
Exercises 432
Chapter 18 Distributed Algorithms 435
Types of Parallelism 436
Systolic Arrays 436
Distributed Computing 438
Multi-CPU Processing 440
Race Conditions 440
Deadlock 444
Quantum Computing 445
Distributed Algorithms 446
Debugging Distributed Algorithms 446
Embarrassingly Parallel Algorithms 447
Mergesort 449

ftoc.indd 05:53:41:PM 07/10/2013 Page xiii


xiv Contents

Dining Philosophers 449


The Two Generals Problem 452
Byzantine Generals 453
Consensus 455
Leader Election 458
Snapshot 459
Clock Synchronization 460
Summary 462
Exercises 462
Chapter 19 Interview Puzzles 465
Asking Interview Puzzle Questions 467
Answering Interview Puzzle Questions 468
Summary 472
Exercises 474
Appendix A Summary of Algorithmic Concepts 477
Appendix B Solutions to Exercises 487

Glossary 559
Index 573

ftoc.indd 05:53:41:PM 07/10/2013 Page xiv


Introduction

Algorithms are the recipes that make efficient programming possible. They
explain how to sort records, search for items, calculate numeric values such as
prime factors, find the shortest path between two points in a street network, and
determine the maximum flow of information possible through a communica-
tions network. The difference between using a good algorithm and a bad one
can mean the difference between solving a problem in seconds, hours, or never.
Studying algorithms lets you build a useful toolkit of methods for solving
specific problems. It lets you understand which algorithms are most effective
under different circumstances so that you can pick the one best suited for a
particular program. An algorithm that provides excellent performance with
one set of data may perform terribly with other data, so it is important that
you know how to pick the algorithm that is the best match for your scenario.
Even more important, by studying algorithms you can learn general problem-
solving techniques that you can apply to other problems even if none of the
algorithms you already know is a perfect fit for your current situation. These
techniques let you look at new problems in different ways so that you can create
and analyze your own algorithms to solve your problems and meet unantici-
pated needs.
In addition to helping you solve problems while on the job, these techniques
may even help you land the job where you can use them! Many large tech-
nology companies, such as Microsoft, Google, Yahoo!, IBM, and others, want
their programmers to understand algorithms and the related problem-solving
techniques. Some of these companies are notorious for making job applicants
work through algorithmic programming and logic puzzles during interviews.
The better interviewers don’t necessarily expect you to solve every puzzle.
In fact, they will probably learn more when you don’t solve a puzzle. Rather

xv
xvi Introduction

than wanting to know the answer, the best interviewers want to see how you
approach an unfamiliar problem. They want to see whether you throw up your
hands and say the problem is unreasonable in a job interview. Or perhaps you
analyze the problem and come up with a promising line of reasoning for using
algorithmic approaches to attack the problem. “Gosh, I don’t know. Maybe I’d
search the Internet,” would be a bad answer. “It seems like a recursive divide-
and-conquer approach might work” would be a much better answer.
This book is an easy-to-read introduction to computer algorithms. It describes
a number of important classical algorithms and tells when each is appropri-
ate. It explains how to analyze algorithms to understand their behavior. Most
importantly, it teaches techniques that you can use to create new algorithms
on your own.
Here are some of the useful algorithms this book describes:
■ Numerical algorithms such as randomization, factoring, working with
prime numbers, and numeric integration
■ Methods for manipulating common data structures such as arrays, linked
lists, trees, and networks
■ Using more-advanced data structures such as heaps, trees, balanced trees,
and B-trees
■ Sorting and searching
■ Network algorithms such as shortest path, spanning tree, topological
sorting, and flow calculations
Here are some of the general problem-solving techniques this book explains:
■ Brute-force or exhaustive search
■ Divide and conquer
■ Backtracking
■ Recursion
■ Branch and bound
■ Greedy algorithms and hill climbing
■ Least-cost algorithms
■ Constricting bounds
■ Heuristics
To help you master the algorithms, this book provides exercises that you
can use to explore ways you can modify the algorithms to apply them to new
situations. This also helps solidify the main techniques demonstrated by the
algorithms.
Introduction xvii

Finally, this book includes some tips for approaching algorithmic questions
that you might encounter in a job interview. Algorithmic techniques let you
solve many interview puzzles. Even if you can’t use algorithmic techniques
to solve every puzzle, you will at least demonstrate that you are familiar with
approaches that you can use to solve other problems.

Algorithm Selection
Each of the algorithms in this book was included for one or more of the fol-
lowing reasons:
■ The algorithm is useful, and a seasoned programmer should be expected
to understand how it works and use it in programs.
■ The algorithm demonstrates important algorithmic programming tech-
niques you can apply to other problems.
■ The algorithm is commonly studied by computer science students, so the
algorithm or the techniques it uses could appear in a technical interview.
After reading this book and working through the exercises, you will have a
good foundation in algorithms and techniques you can use to solve your own
programming problems.

Who This Book Is For


This book is intended primarily for three kinds of readers: professional program-
mers, programmers preparing for job interviews, and programming students.
Professional programmers will find the algorithms and techniques described
in this book useful for solving problems they face on the job. Even when you
encounter a problem that isn’t directly addressed by an algorithm in this book,
reading about these algorithms will give you new perspectives from which to
view problems so that you can find new solutions.
Programmers preparing for job interviews can use this book to hone their
algorithmic skills. Your interviews may not include any of the problems described
in this book, but they may contain questions that are similar enough that you
can use the techniques you learned in this book to solve them.
Programming students should be required to study algorithms. Many of
the approaches described in this book are simple, elegant, and powerful, but
they’re not all obvious, so you won’t necessarily stumble across them on your
own. Techniques such as recursion, divide and conquer, branch and bound, and
using well-known data structures are essential to anyone who has an interest
in programming.
xviii Introduction

NOTE Personally, I think algorithms are just plain fun! They’re my equivalent of
crossword puzzles or Sudoku. I love the feeling of putting together a complicated
algorithm, dumping some data into it, and seeing a beautiful three-dimensional
image, a curve matching a set of points, or some other elegant result appear!

Getting the Most Out of This Book


You can learn some new algorithms and techniques just by reading this book,
but to really master the methods demonstrated by the algorithms, you need to
work with them. You need to implement them in some programming language.
You also need to experiment, modify the algorithms, and try new variations on
old problems. The book’s exercises and interview questions can give you ideas
for new ways to use the techniques demonstrated by the algorithms.
To get the greatest benefit from the book, I highly recommend that you imple-
ment as many of the algorithms as possible in your favorite programming
language or even in more than one language to see how different languages
affect implementation issues. You should study the exercises and at least write
down outlines for solving them. Ideally you should implement them, too. Often
there’s a reason why an exercise is included, and you may not discover it until
you take a hard look at the problem.
Finally, look over some of the interview questions available on the Internet,
and figure out how you would approach them. In many interviews you won’t
be required to implement a solution, but you should be able to sketch out solu-
tions. And if you have time to implement solutions, you will learn even more.
Understanding algorithms is a hands-on activity. Don’t be afraid to put down
the book, break out a compiler, and write some actual code!

This Book’s Websites


Actually, this book has two websites: Wiley’s version and my version. Both sites
contain the book’s source code.
The Wiley web page for this book is http://www.wiley.com/go/essential
algorithms. You also can go to http://www.wiley.com and search for the book
by title or ISBN. Once you’ve found the book, click the Downloads tab to obtain
all the source code for the book. Once you download the code, just decompress it
with your favorite compression tool.

NOTE At the Wiley web site, you may find it easiest to search by ISBN. This
book’s ISBN is 978-1-118-61210-1.
Introduction xix

To find my web page for this book, go to http://www.CSharpHelper.com/


algorithms.html.

How This Book Is Structured


This section describes the book’s contents in detail.
Chapter 1, “Algorithm Basics,” explains concepts you must understand to
analyze algorithms. It discusses the difference between algorithms and data
structures, introduces Big O notation, and describes times when practical con-
siderations are more important than theoretical runtime calculations.
Chapter 2, “Numerical Algorithms,” explains several algorithms that work
with numbers. These algorithms randomize numbers and arrays, calculate greatest
common divisor and least common multiple, perform fast exponentiation, and
determine whether a number is prime. Some of the algorithms also introduce
the important techniques of adaptive quadrature and Monte Carlo simulation.
Chapter 3, “Linked Lists,” explains linked-list data structures. These flex-
ible structures can be used to store lists that may grow over time. The basic
concepts are also important for building other linked data structures, such as
trees and networks.
Chapter 4, “Arrays,” explains specialized array algorithms and data struc-
tures, such as triangular arrays and sparse arrays, that can save a program time
and memory.
Chapter 5, “Stacks and Queues,” explains algorithms and data structures
that let a program store and retrieve items in first-in-first-out (FIFO) or last-in-
first-out (LIFO) order. These data structures are useful in other algorithms and
can be used to model real-world scenarios such as checkout lines at a store.
Chapter 6, “Sorting,” explains sorting algorithms that demonstrate a wide
variety of useful algorithmic techniques. Different sorting algorithms work best
for different kinds of data and have different theoretical run times, so it’s good
to understand an assortment of these algorithms. These are also some of the
few algorithms for which exact theoretical performance bounds are known, so
they are particularly interesting to study.
Chapter 7, “Searching,” explains algorithms that a program can use to search
sorted lists. These algorithms demonstrate important techniques such as binary
subdivision and interpolation.
Chapter 8, “Hash Tables,” explains hash tables—data structures that use extra
memory to allow a program to locate specific items quickly. They powerfully
demonstrate the space-time trade-off that is so important in many programs.
Chapter 9, “Recursion,” explains recursive algorithms—those that call them-
selves. Recursive techniques make some algorithms much easier to understand
xx Introduction

and implement, although they also sometimes lead to problems, so this chapter
also describes how to remove recursion from an algorithm when necessary.
Chapter 10, “Trees,” explains highly recursive tree data structures, which
are useful for storing, manipulating, and studying hierarchical data and have
applications in unexpected places, such as evaluating arithmetic expressions.
Chapter 11, “Balanced Trees,” explains trees that remain balanced as they
grow over time. In general, tree structures can grow very tall and thin, and that
can ruin the performance of tree algorithms. Balanced trees solve this problem
by ensuring that a tree doesn’t grow too tall and skinny.
Chapter 12, “Decision Trees,” explains algorithms that attempt to solve
problems that can be modeled as a series of decisions. These algorithms are
often used on very hard problems, so they often find only approximate solutions
rather than the best solution possible. However, they are very flexible and can
be applied to a wide range of problems.
Chapter 13, “Basic Network Algorithms,” explains fundamental network
algorithms such as visiting all the nodes in a network, detecting cycles, creating
spanning trees, and finding paths through a network.
Chapter 14, “More Network Algorithms,” explains more network algorithms,
such as topological sorting to arrange dependent tasks, graph coloring, network
cloning, and assigning work to employees.
Chapter 15, “String Algorithms,” explains algorithms that manipulate strings.
Some of these algorithms, such as searching for substrings, are built into tools
that most programming languages can use without customized programming.
Others, such as parenthesis matching and finding string differences, require
some extra work and demonstrate useful techniques.
Chapter 16, “Cryptography,” explains how to encrypt and decrypt information.
It covers the basics of encryption and describes several interesting encryption
techniques, such as Vigenère ciphers, block ciphers, and public key encryption.
This chapter does not go into all the details of specific encryption algorithms such
as DES (Data Encryption Standard) and AES (Advanced Encryption Standard),
because they are more appropriate for a book on encryption.
Chapter 17, “Complexity Theory,” explains two of the most important classes
of problems in computer science: P (problems that can be solved in determinis-
tic polynomial time) and NP (problems that can be solved in nondeterministic
polynomial time). This chapter describes these classes, ways to prove that a
problem is in one or the other, and the most profound question in computer
science: Is P equal to NP?
Chapter 18, “Distributed Algorithms,” explains algorithms that run on
multiple processors. Almost all modern computers contain multiple processors,
and computers in the future will contain even more, so these algorithms are
essential for getting the most out of a computer’s latent power.
Introduction xxi

Chapter 19, “Interview Puzzles,” describes tips and techniques you can use
to attack puzzles and challenges that you may encounter during a program-
ming interview. It also includes a list of some websites that contain large lists
of puzzles that you can use for practice.
Appendix A, “Summary of Algorithmic Concepts,” summarizes the ideas
and strategies used by the algorithms described in this book. Using these, you
can build solutions to other problems that are not specifically covered by the
algorithms described here.
Appendix B, “Solutions to Exercises,” contains the solutions to the exercises
at the end of each chapter.
The Glossary defines important algorithmic concepts that are used in this book.
You may want to review the Glossary before going on programming interviews.

What You Need to Use This Book


To read this book and understand the algorithms, you don’t need any special
equipment. If you really want to master the material, however, you should imple-
ment as many algorithms as possible in an actual programming language. It
doesn’t matter which language. Working through the details of implementing
the algorithms in any language will help you better understand the algorithms’
details and any special treatment required by the language.
Of course, if you plan to implement the algorithms in a programming language,
you need a computer and whatever development environment is appropriate.
The book’s websites contain sample implementations written in C# with Visual
Studio 2012 that you can download and examine. If you want to run those, you
need to install C# 2012 on a computer that can run Visual Studio reasonably well.
Running any version of Visual Studio requires that you have a reasonably fast,
modern computer with a large hard disk and lots of memory. For example, I’m
fairly happy running my Intel Core 2 system at 1.83 GHz with 2 GB of memory
and a spacious 500 GB hard drive. That’s a lot more disk space than I need, but
disk space is relatively cheap, so why not buy a lot?
You can run Visual Studio on much less powerful systems, but using an
underpowered computer can be extremely slow and frustrating. Visual Studio
has a big memory footprint, so if you’re having performance problems, install-
ing more memory may help.
The programs will load and execute with C# Express Edition, so there’s no need
to install a more expensive version of C#. You can get more information on C#
Express Edition and download it at http://www.microsoft.com/visualstudio/
eng/downloads#d-express-windows-desktop.
xxii Introduction

Conventions
To help you get the most from the text and keep track of what’s happening, I’ve
used several conventions throughout the book.

SPLENDID SIDEBARS

Sidebars such as this one contain additional information and side topics.

WARNING Warning boxes like this hold important, not-to-be forgotten infor-
mation that is directly relevant to the surrounding text.

NOTE Boxes like this hold notes, tips, hints, tricks, and asides to the current
discussion.

As for styles in the text:


■ New terms and important words are italicized when they are introduced.
You also can find many of them in the Glossary.
■ Keyboard strokes look like this: Ctrl+A. This one means to hold down
the Ctrl key and then press the A key.
■ URLs, code, and email addresses within the text are shown in monofont
type, as in http://www.CSharpHelper.com, x = 10, and RodStephens@
CSharpHelper.com.

We present code in one of two ways:


I use a monofont type with no highlighting for most code examples.

I use bold text to emphasize code that's particularly important


in the present context.

Email Me
If you have questions, comments, or suggestions, please feel free to email me at
RodStephens@CSharpHelper.com. I can’t promise to solve all your algorithmic
problems, but I do promise to try to point you in the right direction.
CHAPTER

Algorithm Basics

Before you jump into the study of algorithms, you need a little background. To
begin with, you need to know that, simply stated, an algorithm is a recipe for
getting something done. It defines the steps for performing a task in a certain way.
That definition seems simple enough, but no one writes algorithms for per-
forming extremely simple tasks. No one writes instructions for how to access
the fourth element in an array. It is just assumed that this is part of the defini-
tion of an array and that you know how to do it (if you know how to use the
programming language in question).
Normally people write algorithms only for difficult tasks. Algorithms explain
how to find the solution to a complicated algebra problem, how to find the short-
est path through a network containing thousands of streets, or how to find the
best mix of hundreds of investments to optimize profits.
This chapter explains some of the basic algorithmic concepts you should
understand if you want to get the most out of your study of algorithms.
It may be tempting to skip this chapter and jump to studying specific
algorithms, but you should at least skim this material. Pay close attention to the
section “Big O Notation,” because a good understanding of runtime performance
can mean the difference between an algorithm performing its task in seconds,
hours, or not at all.

1
Random documents with unrelated
content Scribd suggests to you:
CARDENIO’S SONG, by Motteux

I
What makes me languish and complain?
O, ’tis Disdain!
What yet more fiercely tortures me?
’Tis Jealousy.
How have I my patience lost?
By Absence crost.
Then Hope, farewell, there’s no relief;
I sink beneath oppressing grief;
Nor can a wretch, without despair,
Scorn, Jealousy, and Absence, bear.

II
What in my breast this anguish drove?
Intruding Love.
Who could such mighty ills create?
Blind Fortune’s hate.
What cruel powers my fate approve?
The Powers above.
Then let me bear, and cease to moan;
’Tis glorious thus to be undone:
When these invade, who dares oppose?
Heaven, Love, and Fortune are my foes.

III
Where shall I find a speedy cure?
Oh! Death is sure.
No milder means to set me free?
Inconstancy.
Can nothing else my pains assuage?
Distracting Rage.
What, die or change? Lucinda lose?
O let me rather madness chuse!
O et e at e ad ess c use
But judge, ye gods, what we endure,
When death or madness are a cure!

In the last four lines, Motteux has used more liberty with the
thought of the original than is allowable for a translator. It must be
owned, however, that he has much improved it.
CARDENIO’S SONG, by Smollet

I
Ah! what inspires my woful strain?
Unkind Disdain!
Ah! what augments my misery?
Fell Jealousy!
Or say what hath my patience worn?
An absent lover’s scorn!
The torments then that I endure
No mortal remedy can cure:
For every languid hope is slain
By Absence, Jealousy, Disdain.

II
From Love, my unrelenting foe,
These sorrows flow:
My infant glory’s overthrown
By Fortune’s frown.
Confirm’d in this my wretched state
By the decrees of Fate,
In death alone I hope release
From this compounded dire disease,
Whose cruel pangs to aggravate,
Fortune and Love conspire with Fate!

III
Ah! what will mitigate my doom?
The silent tomb.
Ah! what retrieve departed joy?
Inconstancy!
Or say, can ought but frenzy bear
This tempest of despair!
All other efforts then are vain
To cure this soul-tormenting pain,
o cu e t s sou to e t g pa ,
That owns no other remedy
Than madness, death, inconstancy.

“The torments then that I endure—no mortal remedy can cure.”


Who ever heard of a mortal remedy? or who could expect to be
cured by it? In the next line, the epithet of languid is injudiciously
given to Hope in this place; for a languid or a languishing hope was
already dying, and needed not so powerful a host of murderers to
slay it, as Absence, Jealousy, and Disdain.—In short, the latter
translation appears to me to be on the whole of much inferior merit
to the former. I have remarked, that Motteux excels his rival chiefly
in the translation of those poems that are of a graver cast. But
perhaps he is censurable for having thrown too much gravity into
the poems that are interspersed in this work, as Smollet is
blameable on the opposite account, of having given them too much
the air of burlesque. In the song which Don Quixote composed while
he was doing penance in the Sierra-Morena, beginning Arboles,
Yerbas y Plantas, every stanza of which ends with Del Toboso, the
author intended, that the composition should be quite characteristic
of its author, a ludicrous compound of gravity and absurdity. In the
translation of Motteux there is perhaps too much gravity; but Smollet
has rendered the composition altogether burlesque. The same
remark is applicable to the song of Antonio, beginning Yo sé, Olalla,
que me adoras, and to many of the other poems.
On the whole, I am inclined to think, that the version of Motteux is
by far the best we have yet seen of the Romance of Cervantes; and
that if corrected in its licentious abbreviations and enlargements,
and in some other particulars which I have noticed in the course of
this comparison, we should have nothing to desire superior to it in
the way of translation.
CHAPTER XIII
OTHER CHARACTERISTICS OF COMPOSITION, WHICH RENDER TRANSLATION
DIFFICULT.—ANTIQUATED TERMS—NEW TERMS—VERBA ARDENTIA.—
SIMPLICITY OF THOUGHT AND EXPRESSION—IN PROSE—IN POETRY.—
NAÏVETÉ IN THE LATTER.—CHAULIEU—PARNELL—LA FONTAINE.—SERIES OF
MINUTE DISTINCTIONS MARKED BY CHARACTERISTIC TERMS.—STRADA.—
FLORID STYLE AND VAGUE EXPRESSION.—PLINY’S NATURAL HISTORY.

In the two preceding chapters I have treated pretty fully of what I


have considered as a principal difficulty in translation, the
permutation of idioms. I shall in this chapter touch upon several
other characteristics of composition, which, in proportion as they are
found in original works, serve greatly to enhance the difficulty of
doing complete justice to them in a translation.
1. The poets, in all languages, have a licence peculiar to
themselves, of employing a mode of expression very remote from
the diction of prose, and still more from that of ordinary speech.
Under this licence, it is customary for them to use antiquated terms,
to invent new ones, and to employ a glowing and rapturous
phraseology, or what Cicero terms Verba ardentia. To do justice to
these peculiarities in a translation, by adopting similar terms and
phrases, will be found extremely difficult; yet, without such
assimilation, the translation presents no just copy of the original. It
would require no ordinary skill to transfuse into another language
the thoughts of the following passages, in a similar species of
phraseology:
Antiquated Terms:
For Nature crescent doth not grow alone
In thews and bulk; but as this temple waxes,
The inward service of the mind and soul
Grows wide withal. Perhaps he loves thee now,
And now no soil nor cautel doth besmirch
The virtue of his will.

Shak. Hamlet, act 1.

New Terms:

So over many a tract


Of heaven they march’d, and many a province wide,
Tenfold the length of this terrene: at last
Far in th’ horizon to the north appear’d
From skirt to skirt a fiery region, stretcht
In battailous aspect, and nearer view
Bristl’d with upright beams innumerable
Of rigid spears, and helmets throng’d, and shields
Various with boastful argument pourtrayed.

Paradise Lost, b. 6.

All come to this? the hearts


That spaniel’d me at heels, to whom I gave
Their wishes, do discandy.

Shak. Ant. & Cleop. act 4, sc. 10.

Glowing Phraseology, or Verba ardentia:


Poor naked wretches, wheresoe’er ye are,
That bide the pelting of this pitiless storm,
How shall your houseless heads, and unfed sides,
Your loop’d and window’d raggedness defend you
From seasons such as these? Oh, I have ta’en
Too little care of this: Take physic, pomp!
Expose thyself to feel what wretches feel,
That thou may’st shake the superflux to them,
And show the heavens more just.

Shak. K. Lear.

Tremble, thou wretch,


That hast within thee undivulged crimes,
Unwhipt of justice! Hide thee, thou bloody hand;
Thou perjure, and thou simular of virtue,
That art incestuous! Caitiff, shake to pieces,
That under covert and convenient seeming
Hast practis’d on man’s life! Close pent up guilts,
Rive your concealing continents, and ask
Those dreadful summoners grace.

Ibid.
Can any mortal mixture of Earth’s mould,
Breathe such divine, enchanting ravishment?
Sure something holy lodges in that breast,
And with these raptures moves the vocal air
To testify his 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 smil’d: I have oft heard,
Amidst the flow’ry-kirtled Naiades,
My mother Circe, with the Sirens three,
Culling their potent herbs and baleful drugs,
Who, as they sung, would take the poison’d soul
And lap it in Elysium.——
But such a sacred, and home-felt delight,
Such sober certainty of waking bliss,
I never heard till now.

Milton’s Comus.

2. There is nothing more difficult to imitate successfully in a


translation than that species of composition which conveys just,
simple, and natural thoughts, in plain, unaffected, and perfectly
appropriate terms; and which rejects all those aucupia sermonis,
those lenocinia verborum, which constitute what is properly termed
florid writing. It is much easier to imitate in a translation that kind of
composition (provided it be at all intelligible),[64] which is brilliant
and rhetorical, which employs frequent antitheses, allusions, similes,
metaphors, than it is to give a perfect copy of just, apposite, and
natural sentiments, which are clothed in pure and simple language:
For the former characters are strong and prominent, and therefore
easily caught; whereas the latter have no striking attractions, their
merit eludes altogether the general observation, and is discernible
only to the most correct and chastened taste.
It would be difficult to approach to the beautiful simplicity of
expression of the following passages, in any translation.
“In those vernal seasons of the year, when the air is calm and
pleasant, it were an injury and sullenness against Nature, not to go
out to see her riches, and partake in her rejoicing with heaven and
earth.” Milton’s Tract of Education.
“Can I be made capable of such great expectations, which those
animals know nothing of, (happier by far in this regard than I am, if
we must die alike), only to be disappointed at last? Thus placed, just
upon the confines of another, better world, and fed with hopes of
penetrating into it, and enjoying it, only to make a short appearance
here, and then to be shut out and totally sunk? Must I then, when I
bid my last farewell to these walks, when I close these lids, and
yonder blue regions and all this scene darken upon me and go out;
must I then only serve to furnish dust to be mingled with the ashes
of these herds and plants, or with this dirt under my feet? Have I
been set so far above them in life, only to be levelled with them at
death?” Wollaston’s Rel. of Nature, sect. ix.
3. The union of just and delicate sentiments with simplicity of
expression, is more rarely found in poetical composition than in
prose; because the enthusiasm of poetry prompts rather to what is
brilliant than what is just, and is always led to clothe its conceptions
in that species of figurative language which is very opposite to
simplicity. It is natural, therefore, to conclude, that in those few
instances which are to be found of a chastened simplicity of thought
and expression in poetry, the difficulty of transfusing the same
character into a translation will be great, in proportion to the
difficulty of attaining it in the original. Of this character are the
following beautiful passages from Chaulieu:
Fontenay, lieu délicieux
Où je vis d’abord la lumiere,
Bientot au bout de ma carriere,
Chez toi je joindrai mes ayeux.
Muses, qui dans ce lieu champêtre
Avec soin me fites nourir,
Beaux arbres, qui m’avez vu naitre,
Bientot vous me verrez mourir.

Les louanges de la vie champêtre.


Je touche aux derniers instans
De mes plus belles années,
Et déja de mon printems
Toutes les fleurs sont fanées.
Je ne vois, et n’envisage
Pour mon arriere saison,
Que le malheur d’etre sage,
Et l’inutile avantage
De connoitre la raison.

Autrefois mon ignorance


Me fournissoit des plaisirs;
Les erreurs de l’espérance
Faisoient naitre mes désirs.
A present l’experience
M’apprend que la jouissance
De nos biens les plus parfaits
Ne vaut pas l’impatience
Ni l’ardeur de nos souhaits.
La Fortune à ma jeunesse
Offrit l’éclat des grandeurs;
Comme un autre avec souplesse
J’aurois brigué ses faveurs.
Mais sur le peu de mérite
De ceux qu’elle a bien traités,
J’eus honte de la poursuite
De ses aveugles bontés;
Et je passai, quoique donne
D’éclat, et pourpre, et couronne,
Du mépris de la personne,
Au mépris des dignités.[65]

Poesies diverses de Chaulieu, p. 44.


4. The foregoing examples exhibit a species of composition, which
uniting just and natural sentiments with simplicity of expression,
preserves at the same time a considerable portion of elevation and
dignity. But there is another species of composition, which,
possessing the same union of natural sentiments with simplicity of
expression, is essentially distinguished from the former by its always
partaking, in a considerable degree, of comic humour. This is that
kind of writing which the French characterise by the term naif, and
for which we have no perfectly corresponding expression in English.
“Le naif,” says Fontenelle, “est une nuance du bas.”
In the following fable of Phædrus, there is a naïveté, which I think
it is scarcely possible to transfuse into any translation:

Inops potentem dum vult imitari, perit.

In prato quædam rana conspexit bovem;


Et tacta invidiâ tantæ magnitudinis
Rugosam inflavit pellem: tum natos suos
Interrogavit, an bove esset latior.
Illi negarunt. Rursus intendit cutem
Majore nisu, et simili quæsivit modo
Quis major esset? Illi dixerunt, bovem.
Novissimè indignata, dum vult validius
Inflare sese, rupto jacuit corpore.

It would be extremely difficult to attain, in any translation, the


laconic brevity with which this story is told. There is not a single
word which can be termed superfluous; yet there is nothing wanting
to complete the effect of the picture. The gravity, likewise, of the
narrative when applied to describe an action of the most
consummate absurdity; the self-important, but anxious questions,
and the mortifying dryness of the answers, furnish an example of a
delicate species of humour, which cannot easily be conveyed by
corresponding terms in another language. La Fontaine was better
qualified than any another for this attempt. He saw the merits of the
original, and has endeavoured to rival them; but even La Fontaine
has failed.

Une Grenouille vit un boeuf


Qui lui sembla de belle taille.
Elle, qui n’etoit pas grosse en tout comme un oeuf,
Envieuse s’étend, et s’enfle, et se travaille
Pour égaler l’animal en grosseur;
Disant, Regardez bien ma soeur,
Est ce assez, dites moi, n’y suis-je pas encore?
Nenni. M’y voila donc? Point du tout. M’y voila
Vous n’en approchez point. La chetive pecore
S’enfla si bien qu’elle creva.
Le monde est plein de gens qui ne sont pas plus sages,
Tout bourgeois veut batir comme les grands seigneurs;
Tout prince a des ambassadeurs,
Tout marquis veut avoir des pages.

But La Fontaine himself when original, is equally inimitable. The


source of that naïveté which is the characteristic of his fables, has
been ingeniously developed by Marmontel: “Ce n’est pas un poete
qui imagine, ce n’est pas un conteur qui plaisante; c’est un temoin
present à l’action, et qui veut vous rendre present vous-même. Il
met tout en oeuvre de la meilleure foi du monde pour vous
persuader; et ce sont tous ces efforts, c’est le sérieux avec lequel il
mêle les plus grandes choses avec les plus petites; c’est l’importance
qu’il attache à des jeux d’enfans; c’est l’interêt qu’il prend pour un
lapin et une belette, qui font qu’on est tenté de s’écrier a chaque
instant, Le bon homme! On le disoit de lui dans la societé. Son
caractere n’a fait que passer dans ses fables. C’est du fond de ce
caractere que sont émanés ces tours si naturels, ces expressions si
naïves, ces images si fideles.”
It would require most uncommon powers to do justice in a
translation to the natural and easy humour which characterises the
dialogue in the following fable:
Les animaux malades de la Peste.

Un mal qui répand la terreur,


Mal que le ciel en sa fureur
Inventa pour punir les crimes de la terre,
La peste, (puis qu’il faut l’apeller par son nom),
Capable d’enrichir en un jour L’Acheron,
Faisoit aux animaux la guerre.
Ils ne mouroient pas tous, mais tous etoient frappés.
On n’en voyoit point d’occupés
A chercher le soûtien d’une mourante vie;
Nul mets n’excitoit leur envie.
Ni loups ni renards n’épioient
La douce et l’innocente proye.
Les tourterelles se fuyoient;
Plus d’amour, partant plus de joye.
Le Lion tint conseil, et dit, Mes chers amis,
Je crois que le ciel a permis
Pour nos pechés cette infortune:
Que le plus coupable de nous
Se sacrifie aux traits du céleste courroux;
Peut-être il obtiendra la guérison commune.
L’histoire nous apprend qu’en de tels accidents,
On fait de pareils dévoûements:
Ne nous flattons donc point, voions sans indulgence
L’état de notre conscience.
Pour moi, satisfaisant mes appetits gloutons
J’ai dévoré force moutons;
Que m’avoient-ils fait? Nulle offense:
Même il m’est arrivé quelquefois de manger le Berger.
Je me dévoûrai donc, s’il le faut; mais je pense
Qu’il est bon que chacun s’accuse ainsi que moi;
Car on doit souhaiter, selon toute justice,
Que le plus coupable périsse.
Sire, dit le Renard, vous êtes trop bon roi;
Vos scrupules font voir trop de délicatesse;
Vos scrupules font voir trop de délicatesse;
Eh bien, manger moutons, canaille, sotte espece,
Est-ce un péchê? Non, non: Vous leur fites, seigneur,
En les croquant beaucoup d’honneur:
Et quant au Berger, l’on peut dire
Qu’il etoit digne de tous maux,
Etant de ces gens-là qui sur les animaux
Se font un chimérique empire.
Ainsi dit le Renard, et flatteurs d’applaudir.
On n’osa trop approfondir
Du Tigre, ni de l’Ours, ni des autres puissances
Les moins pardonnables offenses.
Tous les gens querelleurs, jusqu’aux simples mâtins
Au dire de chacun, etoient de petits saints.
L’âne vint à son tour, et dit, J’ai souvenance
Qu’en un pré de moines passant,
La faim, l’occasion, l’herbe tendre, et je pense
Quelque diable aussi me poussant,
Je tondis de ce pré la largeur de ma langue:
Je n’en avois nul droit, puisqu’il faut parler net.
À ces mots on cria haro sur le baudet:
Un loup quelque peu clerc prouva par sa harangue
Qu’il falloit dévoüer ce maudit animal,
Ce pelé, ce galeux, d’ou venoit tout leur mal.
Sa peccadille fut jugee un cas pendable;
Manger l’herbe d’autrui, quel crime abominable!
Rien que la mort n’etoit capable
D’expier son forfait, on le lui fit bien voir.
Selon que vous serez puissant ou misérable,
Les jugements de cour vous rendront blanc ou noir.

5. No compositions will be found more difficult to be translated,


than those descriptions, in which a series of minute distinctions are
marked by characteristic terms, each peculiarly appropriated to the
thing to be designed, but many of them so nearly synonymous, or so
approaching to each other, as to be clearly understood only by those
who possess the most critical knowledge of the language of the
original, and a very competent skill in the subject treated of. I have
always regarded Strada’s Contest of the Musician and Nightingale, as
a composition which almost bids defiance to the art of a translator.
The reader will easily perceive the extreme difficulty of giving the
full, distinct, and appropriate meaning of those expressions marked
in Italics.
Jam Sol a medio pronus deflexerat orbe,
Mitius e radiis vibrans crinalibus ignem:
Cum fidicen propter Tiberina fluenta, sonanti
Lenibat plectro curas, æstumque levabat,
Ilice defensus nigra, scenaque virenti.
Audiit hunc hospes sylvæ philomela propinquæ,
Musa loci, nemoris Siren, innoxia Siren;
Et prope succedens stetit abdita frondibus, altè
Accipiens sonitum, secumque remurmurat, et quos
Ille modos variat digitis, hæc gutture reddit.

Sensit se fidicen philomela imitante referri,


Et placuit ludum volucri dare; plenius ergo
Explorat citharam, tentamentumque futuræ
Præbeat ut pugnæ, percurrit protinus omnes
Impulsu pernice fides. Nec segnius illa
Mille per excurrens variæ discrimina vocis,
Venturi specimen præfert argutula cantûs.

Tunc fidicen per fila movens trepidantia dextram,


Nunc contemnenti similis diverberat ungue,
Depectitque pari chordas et simplice ductu:
Nunc carptim replicat, digitisque micantibus urget,
Fila minutatim, celerique repercutit ictu.
Mox silet. Illa modis totidem respondet, et artem
Arte refert. Nunc, ceu rudis aut incerta canendi,
Projicit in longum, nulloque plicatile flexu,
Carmen init simili serie, jugique tenore
Præbet iter liquidum labenti e pectore voci:
Nunc cæsim variat, modulisque canora minutis
Delibrat vocem, tremuloque reciprocat ore.

Miratur fidicen parvis è faucibus ire


Tam varium, tam dulce melos: majoraque tentans,
Alternat mira arte fides; dum torquet acutas
Inciditque graves operoso verbere pulsat
Inciditque, graves operoso verbere pulsat,
Permiscetque simul certantia rauca sonoris;
Ceu resides in bella viros clangore lacessat.
Hoc etiam philomela canit: dumque ore liquenti
Vibrat acuta sonum, modulisque interplicat æquis;
Ex inopinato gravis intonat, et leve murmur
Turbinat introrsus, alternantique sonore,
Clarat et infuscat, ceu martia classica pulset.

Scilicet erubuit fidicen, iraque calente,


Aut non hoc, inquit, referes, citharistia sylvæ,
Aut fractâ cedam citharâ. Nec plura locutus,
Non imitabilibus plectrum concentibus urget.
Namque manu per fila volat, simul hos, simul illos
Explorat numeros, chordâque laborat in omni;
Et strepit et tinnit, crescitque superbius, et se
Multiplicat relegens, plenoque choreumate plaudit.
Tum stetit expectans si quid paret æmula contra.

Illa autem, quanquam vox dudum exercita fauces


Asperat, impatiens vinci, simul advocat omnes
Necquicquam vires: nam dum discrimina tanta
Reddere tot fidium nativa et simplice tentat
Voce, canaliculisque imitari grandia parvis,
Impar magnanimis ausis, imparque dolori,
Deficit, et vitam summo in certamine linquens,
Victoris cadit in plectrum, par nacta sepulchrum.

He that should attempt a translation of this most artful


composition, dum tentat discrimina tanta reddere, would probably,
like the nightingale, find himself impar magnanimis ausis.[66]
It must be here remarked, that Strada has not the merit of
originality in this characteristic description of the song of the
Nightingale. He found it in Pliny, and with still greater amplitude, and
variety of discrimination. He seems even to have taken from that
author the hint of his fable: “Digna miratu avis. Primum, tanta vox
tam parvo in corpusculo, tam pertinax spiritus. Deinde in una
perfecta musicæ scientia modulatus editur sonus; et nunc continuo
spiritu trahitur in longum, nunc variatur inflexo, nunc distinguitur
conciso, copulatur intorto, promittitur revocato, infuscatur ex
inopinato: interdum et secum ipse murmurat, plenus, gravis, acutus,
creber, extentus; ubi visum est vibrans, summus, medius, imus.
Breviterque omnia tam parvulis in faucibus, quæ tot exquisitis
tibiarum tormentis ars hominum excogitavit.—Certant inter se,
palamque animosa contentio est. Victa morte finit sæpe vitam,
spiritu prius deficiente quam cantu.” Plin. Nat. Hist. lib. 10, c. 29.
It would perhaps be still more difficult to give a perfect translation
of this passage from Pliny, than of the fable of Strada. The attempt,
however, has been made by an old English author, Philemon Holland;
and it is curious to remark the extraordinary shifts to which he has
been reduced in the search of corresponding expressions:

Explorat numeros, chordaque laborat in omni.

“Surely this bird is not to be set in the last place of those that
deserve admiration; for is it not a wonder, that so loud and clear a
voice should come from so little a body? Is it not as strange, that
shee should hold her wind so long, and continue with it as shee
doth? Moreover, shee alone in her song keepeth time and measure
truly, she riseth and falleth in her note just with the rules of music,
and perfect harmony; for one while, in one entire breath she drawes
out her tune at length treatable; another while she quavereth, and
goeth away as fast in her running points: sometimes she maketh
stops and short cuts in her notes; another time she gathereth in her
wind, and singeth descant between the plain song: she fetcheth in
her breath again, and then you shall have her in her catches and
divisions: anon, all on a sudden, before a man would think it, she
drowneth her voice that one can scarce heare her; now and then
she seemeth to record to herself, and then she breaketh out to sing
voluntarie. In sum, she varieth and altereth her voice to all keies:
one while full of her largs, longs, briefs, semibriefs, and minims;
another while in her crotchets, quavers, semiquavers, and double
semiquavers: for at one time you shall hear her voice full of loud,
another time as low; and anon shrill and on high; thick and short
when she list; drawn out at leisure again when she is disposed; and
then, (if she be so pleased), shee riseth and mounteth up aloft, as it
were with a wind organ. Thus shee altereth from one to another,
and sings all parts, the treble, the mean, and the base. To conclude,
there is not a pipe or instrument devised with all the art and cunning
of man, that can affoord more musick than this pretty bird doth out
of that little throat of hers.—They strive who can do best, and one
laboreth to excel another in variety of song and long continuance;
yea, and evident it is that they contend in good earnest with all their
will and power: for oftentimes she that hath the worse, and is not
able to hold out with another, dieth for it, and sooner giveth she up
her vitall breath, than giveth over her song.”
The consideration of the above passage in the original, leads to
the following remark.
5. There is no species of writing so difficult to be translated, as
that where the character of the style is florid, and the expression
consequently vague, and of indefinite meaning. The natural history
of Pliny furnishes innumerable examples of this fault; and hence it
will ever be found one of the most difficult works to be translated. A
short chapter shall be here analyzed, as an instructive specimen.
Lib. 11, Cap. 2.
In magnis siquidem corporibus, aut certe majoribus, facilis officina
sequaci materia fuit. In his tam parvis atque tam nullis, quæ ratio,
quanta vis, quam inextricabilis perfectio! Ubi tot sensus collocavit in
culice? Et sunt alia dictu minora. Sed ubi visum in eo prætendit? Ubi
gustatum applicavit? Ubi odoratum inseruit? Ubi vero truculentam
illam et portione maximam vocem ingeneravit? Qua subtilitate
pennas adnexuit? Prælongavit pedum crura? disposuit jejunam
caveam, uti alvum? Avidam sanguinis et potissimum humani sitim
accendit? Telum vero perfodiendo tergori, quo spiculavit ingenio?
Atque ut in capaci, cum cerni non possit exilitas, ita reciproca
geminavit arte, ut fodiendo acuminatum, pariter sorbendoque
fistulosum esset. Quos teredini ad perforanda robora cum sono teste
dentes affixit? Potissimumque e ligno cibatum fecit? Sed turrigeros
elephantorum miramur humeros, taurorumque colla, et truces in
sublime jactus, tigrium rapinas, leonum jubas; cùm rerum natura
nusquam magis quam in minimis tota sit. Quapropter quæso, ne
hæc legentes, quoniam ex his spernunt multa, etiam relata fastidio
damnent, cùm in contemplatione naturæ, nihil possit videri
supervacuum.
Although, after the perusal of the whole of this chapter, we are at
no loss to understand its general meaning, yet when it is taken to
pieces, we shall find it extremely difficult to give a precise
interpretation, much less an elegant translation of its single
sentences. The latter indeed may be accounted impossible, without
the exercise of such liberties as will render the version rather a
paraphrase than a translation. In magnis siquidem corporibus, aut
certe majoribus, facilis officina sequaci materiæ fuit. The sense of
the term magnus, which is in itself indefinite, becomes in this
sentence much more so, from its opposition to major; and the
reader is quite at a loss to know, whether in those two classes of
animals, the magni and the majores, the largest animals are
signified by the former term, or by the latter. Had the opposition
been between magnus and maximus, or major and maximus, there
could not have been the smallest ambiguity. Facilis officina sequaci
materiæ fuit. Officina is the workhouse where an artist exercises his
craft; but no author, except Pliny himself, ever employed it to signify
the labour of the artist. With a similar incorrectness of expression,
which, however, is justified by general use, the French employ
cuisine to signify both the place where victuals are dressed, and the
art of dressing them. Sequax materia signifies pliable materials, and
therefore easily wrought; but the term sequax cannot be applied
with any propriety to such materials as are easily wrought, on
account of their magnitude or abundance. Tam parvis is easily
understood, but tam nullis has either no meaning at all, or a very
obscure one. Inextricabilis perfectio. It is no perfection in anything to
be inextricable; for the meaning of inextricable is, embroiled,
perplexed, and confounded. Ubi tot sensus collocavit in culice? What
is the meaning of the question ubi? Does it mean, in what part of
the body of the gnat? I conceive it can mean nothing else: And if so,
the question is absurd; for all the senses of a gnat are not placed in
any one part of its body, any more than the senses of a man. Dictu
minora. By these words the author intended to convey the meaning
of alia etiam minora possunt dici; but the meaning which he has
actually conveyed is, Sunt alia minora quam quæ dici possunt, which
is false and hyperbolical; for no insect is so small that words may not
be found to convey an idea of its size. Portione maximam vocem
ingeneravit. What is portione maximam? It is only from the context
that we guess the author’s meaning to be, maximam ratione
portionis, i. e. magnitudinis insecti; for neither use, nor the analogy
of the language, justify such an expression as vocem maximam
portione. If it is alledged, that portio is here used to signify the
power or intensity of the voice, and is synonymous in this place to
vis, ενεργεια, we may safely assert, that this use of the term is
licentious, improper, and unwarranted by custom. Jejunam caveam
uti alvum; “a hungry cavity for a belly:” but is not the stomach of all
animals a hungry cavity, as well as that of the gnat? Capaci cum
cernere non potest exilitas. Capax is improperly contrasted with
exilis, and cannot be otherwise translated than in the sense of
magnus. Reciproca geminavit arte is incapable of any translation
which shall render the proper sense of the words, “doubled with
reciprocal art.” The author’s meaning is, “fitted for a double
function.” Cum sono teste is guessed from the context to mean, uti
sonus testatur. Cum rerum natura nusquam magis quam in minimis
tota sit. This is a very obscure expression of a plain sentiment, “The
wisdom and power of Providence, or of Nature, is never more
conspicuous than in the smallest bodies.” Ex his spernunt multa. The
meaning of ex his is indefinite, and therefore obscure: we can but
conjecture that it means ex rebus hujusmodi; and not ex his quæ
diximus; for that sense is reserved for relata.
From this specimen, we may judge of the difficulty of giving a just
translation of Pliny’s Natural History.
CHAPTER XIV
OF BURLESQUE TRANSLATION.—TRAVESTY AND PARODY.—SCARRON’S VIRGILE
TRAVESTI.—ANOTHER SPECIES OF LUDICROUS TRANSLATION.

In a preceding chapter, while treating of the translation of


idiomatic phrases, we censured the use of such idioms in the
translation as do not correspond with the age or country of the
original. There is, however, one species of translation, in which that
violation of the costume is not only blameless, but seems essential
to the nature of the composition: I mean burlesque translation, or
Travesty. This species of writing partakes, in a great degree, of
original composition; and is therefore not to be measured by the
laws of serious translation. It conveys neither a just picture of the
sentiments, nor a faithful representation of the style and manner of
the original; but pleases itself in exhibiting a ludicrous caricatura of
both. It displays an overcharged and grotesque resemblance, and
excites our risible emotions by the incongruous association of dignity
and meanness, wisdom and absurdity. This association forms equally
the basis of Travesty and of Ludicrous Parody, from which it is no
otherwise distinguished than by its assuming a different language
from the original. In order that the mimickry may be understood, it
is necessary that the writer choose, for the exercise of his talents, a
work that is well known, and of great reputation. Whether that
reputation is deserved or unjust, the work may be equally the
subject of burlesque imitation. If it has been the subject of general,
but undeserved praise, a Parody or a Travesty is then a fair satire on
the false taste of the original author, and his admirers, and we are
pleased to see both become the objects of a just castigation. The
Rehearsal, Tom Thumb, and Chrononhotonthologos, which exhibit
ludicrous parodies of passages from the favourite dramatic writers of
the times, convey a great deal of just and useful criticism. If the
original is a work of real excellence, the Travesty or Parody detracts
nothing from its merit, nor robs the author of the smallest portion of
his just praise.[67] We laugh at the association of dignity and
meanness; but the former remains the exclusive property of the
original, the latter belongs solely to the copy. We give due praise to
the mimical powers of the imitator, and are delighted to see how
ingeniously he can elicit subject of mirth and ridicule from what is
grave, dignified, pathetic, or sublime.
In the description of the games in the 5th Æneid, Virgil
everywhere supports the dignity of the Epic narration. His persons
are heroes, their actions are suitable to that character, and we feel
our passions seriously interested in the issue of the several contests.
The same scenes travestied by Scarron are ludicrous in the extreme.
His heroes have the same names, they are engaged in the same
actions, they have even a grotesque resemblance in character to
their prototypes; but they have all the meanness, rudeness, and
vulgarity of ordinary prize-fighters, hackney coachmen, horse-
jockeys, and water-men.

Medio Gyas in gurgite victor


Rectorem navis compellat voce Menœtem;
Quo tantum mihi dexter abis? huc dirige cursum,
Littus ama, et lævas stringat sine palmula cautes;
Altum alii teneant. Dixit: sed cæca Menœtes
Saxa timens, proram pelagi detorquet ad undas.
Quo diversus abis? iterum pete saxa, Menœte,
Cum clamore Gyas revocabat.
Gyas, qui croit que son pilote,
Comme un vieil fou qu’il est, radote,
De ce qu’en mer il s’elargit,
Aussi fort qu’un lion rugit;
Et s’ecrie, écumant de rage,
Serre, serre donc le rivage,
Fils de putain de Ménétus,
Serre, ou bien nous somme victus:
Serre donc, serre à la pareille:
Ménétus fit la sourde oreille,
Et s’éloigne toujours du bord,
Et si pourtant il n’a pas tort:
Habile qu’il est, il redoute
Certains rocs, ou l’on ne voit goute—
Lors Gyas se met en furie,
Et de rechef crie et recrie,
Vieil coyon, pilote enragé,
Mes ennemis t’ont ils gagé
Pour m’oter l’honneur de la sorte?
Serre, ou que le diable t’emporte,
Serre le bord, ame de chien:
Mais au diable, s’il en fait rien.

In Virgil, the prizes are suitable to the dignity of the persons who
contend for them:

Munera principio ante oculos, circoque locantur


In medio: sacri tripodes, viridesque coronæ,
Et palmæ, pretium victoribus; armaque, et ostro
Perfusæ vestes, argenti aurique talenta.

In Scarron, the prizes are accommodated to the contending


parties with equal propriety:
Maitre Eneas faisant le sage, &c.
Fit apporter une marmitte,
C’etoit un des prix destinés,
Deux pourpoints fort bien galonnés
Moitié filet et moitié soye,
Un sifflet contrefaisant l’oye,
Un engin pour casser des noix,
Vingt et quatre assiettes de bois,
Qu’Eneas allant au fourrage
Avoit trouvé dans le bagage
Du vénérable Agamemnon:
Certain auteur a dit que non,
Comptant la chose d’autre sorte,
Mais ici fort peu nous importe:
Une toque de velous gras,
Un engin à prendre des rats,
Ouvrage du grand Aristandre,
Qui savoit bien les rats prendre
En plus de cinquante façons,
Et meme en donnoit des leçons:
Deux tasses d’etain émaillées,
Deux pantoufles despareillées,
Dont l’une fut au grand Hector,
Toutes deux de peau de castor—
Et plusieurs autres nippes rares, &c.

But this species of composition pleases only in a short specimen.


We cannot bear a lengthened work in Travesty. The incongruous
association of dignity and meanness excites risibility chiefly from its
being unexpected. Cotton’s and Scarron’s Virgil entertain but for a
few pages: the composition soon becomes tedious, and at length
disgusting. We laugh at a short exhibition of buffoonery; but we
cannot endure a man, who, with good talents, is constantly playing
the fool.
There is a species of ludicrous verse translation which is not of the
nature of Travesty, and which seems to be regulated by all the laws
of serious translation. It is employed upon a ludicrous original, and
its purpose is not to burlesque, but to represent it with the utmost
fidelity. For that purpose, even the metrical stanza is closely
imitated. The ludicrous effect is heightened, when the stanza is
peculiar in its structure, and is transferred from a modern to an
ancient language; as in Dr. Aldrich’s translation of the well-known
song,

A soldier and a sailor,


A tinker and a tailor,
Once had a doubtful strife, Sir,
To make a maid a wife, Sir,
Whose name was buxom Joan, &c.

Miles et navigator,
Sartor et ærator,
Jamdudum litigabant,
De pulchra quam amabant,
Nomen cui est Joanna, &c.

Of the same species of translation is the facetious composition


intitled Ebrii Barnabæ Itinerarium, or Drunken Barnaby’s Journal:

O Faustule, dic amico,


Quo in loco, quo in vico,
Sive campo, sive tecto,
Sine linteo, sine lecto;
Propinasti queis tabernis,
An in terris, an Avernis.
Little Fausty, tell thy true heart,
In what region, coast, or new part,
Field or fold, thou hast been bousing,
Without linen, bedding, housing;
In what tavern, pray thee, show us,
Here on earth, or else below us:

And the whimsical, though serious translation of Chevy-chace:

Vivat Rex noster nobilis,


Omnis in tuto sit;
Venatus olim flebilis
Chevino luco fit.

God prosper long our noble King,


Our lives and safeties all:
A woful hunting once there did
In Chevy-chace befal, &c.

You might also like