100% found this document useful (1 vote)
9 views

Essential Algorithms a Practical Approach to Computer Algorithms 1st Edition Rod Stephens pdf download

Essential Algorithms: A Practical Approach to Computer Algorithms by Rod Stephens provides a comprehensive guide to various algorithms and data structures, covering topics from basic algorithm concepts to advanced techniques like cryptography and distributed algorithms. The book includes practical examples, exercises, and a glossary, making it suitable for both beginners and experienced programmers. It is published by John Wiley & Sons and is available in multiple formats for download.

Uploaded by

picotequasie
Copyright
© © All Rights Reserved
We take content rights seriously. If you suspect this is your content, claim it here.
Available Formats
Download as PDF, TXT or read online on Scribd
100% found this document useful (1 vote)
9 views

Essential Algorithms a Practical Approach to Computer Algorithms 1st Edition Rod Stephens pdf download

Essential Algorithms: A Practical Approach to Computer Algorithms by Rod Stephens provides a comprehensive guide to various algorithms and data structures, covering topics from basic algorithm concepts to advanced techniques like cryptography and distributed algorithms. The book includes practical examples, exercises, and a glossary, making it suitable for both beginners and experienced programmers. It is published by John Wiley & Sons and is available in multiple formats for download.

Uploaded by

picotequasie
Copyright
© © All Rights Reserved
We take content rights seriously. If you suspect this is your content, claim it here.
Available Formats
Download as PDF, TXT or read online on Scribd
You are on page 1/ 63

Essential Algorithms a Practical Approach to

Computer Algorithms 1st Edition Rod Stephens pdf


download

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

Get Instant Ebook Downloads – Browse 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/

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/

Algorithms in C Computer Science Series 1st Edition


Sedgewick

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

Till A Glacial Process Sedimentology 1st Edition David


J. A. Evans

https://ebookname.com/product/till-a-glacial-process-
sedimentology-1st-edition-david-j-a-evans/
Clinical Trials in Oncology 2ed. Edition Stephanie
Green

https://ebookname.com/product/clinical-trials-in-oncology-2ed-
edition-stephanie-green/

Encyclopedia of Business Finance 2nd Edition Burton S.


Kaliski

https://ebookname.com/product/encyclopedia-of-business-
finance-2nd-edition-burton-s-kaliski/

System Health Management with Aerospace Applications


1st Edition Stephen B. Johnson

https://ebookname.com/product/system-health-management-with-
aerospace-applications-1st-edition-stephen-b-johnson/

Berkshire Encyclopedia of World History 2nd Ed 2nd


Edition William H. Mcneill

https://ebookname.com/product/berkshire-encyclopedia-of-world-
history-2nd-ed-2nd-edition-william-h-mcneill/

Unfamiliar Relations Family and History in South Asia


1st Edition Edition Indrani Chatterjee (Ed.)

https://ebookname.com/product/unfamiliar-relations-family-and-
history-in-south-asia-1st-edition-edition-indrani-chatterjee-ed/
Testing Global Interdependence Issues on Trade Aid
Migration and Development Ernest Aryeetey

https://ebookname.com/product/testing-global-interdependence-
issues-on-trade-aid-migration-and-development-ernest-aryeetey/
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
Another Random Document on
Scribd Without Any Related Topics
vengeance to fall upon them; and said, moreover, “I cair not, my
lordis, your displeasour; for I speik my conscience befoir God,
wha will not suffer sic wickitnes and contempt vnpunished.”’
Bannatyne's Journal, edit. Edinburgh, 1806, p. 257.
[207] In 1576, the General Assembly declared, that their right
to ‘the patrimonie of the Kirk’ was ‘ex jure divino.’ Acts of the
General Assemblies of the Kirk of Scotland, vol. i. p. 360,
Edinburgh, 1839, 4to. More than a hundred years later, a Scotch
divine evinces how deeply the members of his profession felt this
spoliation of the Church, by going out of his way to mention it.
See Jacob's Vow, by Dr. John Cockburn, Edinburgh, 1696, pp.
422, 423, 425. But this is nothing in comparison to a recent
writer, the Reverend Mr. Lyon, who deliberately asserts that,
because these and similar acts occurred in the reign of Mary,
therefore the queen came to a violent end; such being the just
punishment of sacrilege. ‘The practice’ (of saying masses for the
dead) ‘ceased, of course, at the Reformation; and the money was
transferred by Queen Mary to the civil authorities of the town.
This was, undoubtedly, an act of sacrilege; for, though sacrificial
masses for the dead was an error, yet the guardians of the money
so bequeathed, were under an obligation to apply it to a sacred
purpose. This, and other sacrilegious acts on the part of Mary, of
a still more decided and extensive character, have been justly
considered as the cause of all the calamities which subsequently
befell her.’ History of St. Andrews, by the Rev. C. J. Lyon, M.A.,
Presbyter of the Episcopal Church, St. Andrews, Edinburgh, 1843,
vol. i. p. 54. Elsewhere (vol. ii. p. 400) the same divine mentions,
that the usual punishment for sacrilege is a failure of male issue.
‘The following examples, selected from the diocese of St.
Andrews, according to its boundaries before the Reformation, will
corroborate the general doctrine contended for throughout this
work, that sacrilege has ever been punished in the present life,
and chiefly by the failure of male issue.’ The italics are in the text.
See also vol. i. p. 118. For the sake of the future historian of
public opinion, it may be well to observe, that the work
containing these sentiments is not a reprint of an older book, but
was published for the first time in 1843, having apparently been
just written.
[208] ‘The General Assemblie of the Kirk of Scotland, convenit
at Edinburgh the 25 of December 1566, to the Nobilitie of this
Realme that professes the Lord Jesus with them, and hes
renouncit that Roman Antichryst, desyre constancie in faith, and
the spirit of righteous judgement. Seeing that Sathan, be all our
negligence, Right Honourable, hes so farre prevailit within this
Realme within these late dayes, that we doe stand in extream
danger, not only to lose our temporall possessions, but also to be
depryvit of the glorious Evangell,’ &c. Keith's Church and State,
vol. iii. pp. 154, 155.
[209] In 1566, in their piteous communication to the English
bishops and clergy, they said ‘The days are ill; iniquitie abounds;
Christian charity, alas, is waxen cold.’ Acts and Proceedings of the
General Assemblies of the Kirk of Scotland, vol. i. p. 87,
Edinburgh, 1839, 4to.
[210] ‘I see twa partis freely gevin to the Devill, and the thrid
maun be devided betwix God and the Devill: Weill, bear witnes to
me, that this day I say it, or it be long the Devill shall have three
partis of the thrid; and judge you then what Goddis portioun
shallbe.’ … ‘Who wold have thought, that when Joseph reulled
Egypt, that his brethren should have travailled for vittallis, and
have returned with empty seckis unto thair families? Men wold
rather have thought that Pharao's pose, treasure, and garnallis
should have bene diminished, or that the houshold of Jacob
should stand in danger to sterve for hungar.’ Knox's History of the
Reformation, vol. ii. pp. 310, 311.
[211] In May 1571, ‘This Sonday, Mr. Craig teiched the 130
Psalme; and, in his sermond, he compared the steat of the Kirk of
God in this tovne vnto the steat of the Maccabeis; wha were
oppressed sumtymes by the Assyrianis and sumtymes by the
Egiptianis.’ Bannatyne's Journal, p. 150.
[212] The first instance I have observed of any thing like
menace, is in 1567, when ‘the Assembly of the Church being
convened at Edinburgh,’ admonished all persons ‘as well
noblemen as barons, and those of the other Estates, to meet and
give their personal appearance at Edinburgh on the 20th of July,
for giving their advice, counsel, and concurrence in matters then
to be proponed; especially for purging the realm of popery, the
establishing of the policy of the Church, and restoring the
patrimony thereof to the just possessors. Assuring those that
should happen to absent themselves at the time, due and lawful
advertisement being made, that they should be reputed hinderers
of the good work intended, and as dissimulate professors be
esteemed unworthy of the fellowship of Christ's flock.’
Spottiswoode's History of the Church of Scotland, vol. ii. p. 64.
This evidently alludes to the possibility of excommunicating those
who would not surrender to the Protestant preachers, the
property stolen from the Catholic Church; and, in 1570, we find
another step taken in the same direction. Under that year, the
following passage occurs in Acts and Proceedings of the General
Assemblies of the Kirk of Scotland, vol. i. p. 181. ‘Q. If those that
withold the duty of the Kirk, wherethrough Ministers want their
stipends, may be excommunicate? A. All things beand done that
the civill ordour requyres of them that withhaldis the duetie of the
Kirk, quherby Ministers wants their stipends; the Kirk may
proceed to excommunication, for their contempt.’
[213] In 1526, ‘the poore ministers, exhorters, and readers,
compleaned at church assembleis, that neither were they able to
live upon the stipends allowed, nor gett payment of that small
portioun which was allowed.’ Calderwood's History of the Kirk,
vol. ii. p. 172. Compare Acts of the General Assemblies, 1839,
4to, vol. i. p. 53; ‘To requyre payment to ministers of there
stipends for the tyme by past, according to the promise made.’
This was in December 1564. In December 1565, the General
Assembly said (p. 71), ‘that wher oft and divers tymes promise
hes bein made to us, that our saids brethren, travelers and
preachers in the Kirk of God, sould not be defraudit of their
appointit stipends, neither zet in any wayes sould be molestit in
their functioun; zet nottheless universallie they want ther stipends
appointit for diverse tymes by past.’ On the state of things in
1566, see ‘The Supplication of the Ministers to the Queen,’ in
Knox's History of the Reformation, vol. ii. p. 529. See also, in the
Miscellany of the Spalding Club, vol. iv. pp. 92–101, Aberdeen,
1849, 4to, a letter written by John Erskine in December 1571,
especially p. 97; ‘the gretest of the nobilitie haifing gretest rentis
in possessione, and plaicet of God in maist hie honouris, ceasis
nocht, maist wiolentlie blindit with awarice, to spoilye and draw to
thame selfis the possessiones of the Kirk.’
[214] ‘The ministers were called proud knaves, and receaved
manie injurious words from the lords, speciallie from Morton, who
ruled all. He said, he sould lay their pride, and putt order to
them.’ Calderwood's History of the Kirk, vol. iii. pp. 137, 138. This
was in 1571.
[215] Chambers' Annals of Scotland, vol. i. pp. 79, 80.
[216] ‘The nobilitie wnderwrittin convenit in Edinburgh, and
chesit and electit James erle of Mortoun regent.’ A Diurnal of
Occurrents, p. 320.
[217] In 1573, ‘when any benefeces of Kirk vaikit, he keapit the
proffet of thair rents sa lang in his awin hand, till he was urgit be
the Kirk to mak donatioun tharof, and that was not gevin but
proffeit for all that.’ The Historie and Life of King James the Sext,
edit. Edinburgh, 1825, 4to, p. 147. Even in 1570, when Lennox
was regent, ‘the Earle of Mortoun was the chiefe manager of
every thing under him;’ and was ‘master of the church rents,’ and
made ‘gifts of them to the nobility.’ Wodrow's Collections upon the
Lives of the Reformers of the Church of Scotland, vol. i. part i. pp.
27, 126, Glasgow, 1834, 4to.
[218] ‘During all these Assembleis and earnest endeavoures of
the brethrein, the regent was often required to give his presence
to the Assemblie, and further the caus of God. He not onlie
refused, but threatned some of the most zealous with hanging,
alledging, that otherwise there could be no peace nor order in the
countrie.’ Calderwood's History of the Kirk, vol. iii. pp. 393, 394.
‘Uses grait thretning against the maist zelus breithring, schoring
to hang of thame, utherwayes ther could be na peace nor ordour
in the countrey.’ The Autobiography and Diary of James Melvill,
edited by R. Pitcairn, Edinburgh, 1842, pp. 59, 60.
[219] ‘He mislyked the Generall Assembleis, and would have
had the name changed, that he might take away the force and
priviledge thereof; and no questioun he had stayed the work of
policie that was presentlie in hands, if God had not stirred up a
factioun against him.’ Calderwood's History of the Kirk of
Scotland, vol. iii. p. 396. See also The Autobiography of James
Melvill, p. 61.
[220] ‘During the two years following the death of Knox, each
day was ripening the more determined opposition of the Church.
The breach between the clergy with the great body of the people,
and the government or higher nobility, was widening rapidly.’
Argyll's Presbytery Examined, p. 70.
[221] ‘Next to her Reformer, who, under God, emancipated her
from the degrading shackles of papal superstition and tyranny, I
know no individual from whom Scotland has received such
important services, or to whom she continues to owe so deep a
debt of national respect and gratitude, as Andrew Melville.’
M'Crie's Life of Andrew Melville, vol. ii. p. 473, Edinburgh, 1819.
His nephew, himself a considerable person, says, ‘Scotland
receavit never a graitter benefit at the hands of God nor this
man.’ The Autobiography of James Melvill, p. 38.
[222] He left Scotland in 1564, at the age of nineteen, and
returned ‘in the beginning of July 1574, after an absence of ten
years from his native country.’ M'Crie's Life of Andrew Melville,
vol. i. pp. 17, 57. See also Scot's Apologetical Narration of the
State of the Kirk of Scotland, edit. Wodrow Society, p. 34; and
Howie's Biographia Scoticana, p. 111, Glasgow, 1781.
[223] He appears to have first set to work in November 1574.
See Stephen's History of the Church of Scotland, vol. i. p. 261,
London, 1848.
[224] ‘The compilers of the Book of Discipline’ (i.e. the First
Book, in 1560) ‘were distinguished by prelatical principles to the
end of their days.’ … ‘That Knox himself was no enemy to prelacy,
considered as an ancient and apostolical institution, is rendered
clear by his “Exhortation to England for the speedy embracing of
Christ's Gospel.”’ Russell's History of the Church in Scotland,
1834, vol. i. p. 240. ‘The associates of Knox, it is obvious, were
not Presbyterians, and had no intention of setting up a system of
parity among the ministers of their new establishment.’ p. 243.
See also p. 332. Even in 1572, the year of Knox's death, I find it
stated that ‘the whole Diocie of Sanct Andrews is decerned be the
Assembly to pertain to the Bishop of the same.’ Acts and
Proceedings of the General Assemblies of the Kirk of Scotland,
vol. i. p. 264, 4to. 1839. The Scotch Presbyterians have dealt very
unfairly with this part of the history of their Church.
[225] Some little time after this, David Fergusson, who died in
1598, and was minister at Dunfermline, said very frankly to James
VI., ‘Yes, Sir, ye may have Bishops here, but ye must remember to
make us all equall; make us all Bishops, els will ye never content
us.’ Row's History of the Kirk of Scotland from 1558 to 1637, edit.
Wodrow Society, p. 418. Compare Calderwood's History of the
Kirk, vol. iv. p. 214: in 1584 ‘these monstruous titles of
superioritie.’ In 1586, ‘that tyrannicall supremacie of bishops and
archbishops over ministers.’ p. 604.
[226] ‘He stirred up John Dury, one of the ministers of
Edinburgh, in an Assembly which was then convened, to
propound a question touching the lawfulness of the episcopal
function, and the authority of chapters in their election. He
himself, as though he had not been acquainted with the motion,
after he had commended the speaker's zeal, and seconded the
purpose with a long discourse of the flourishing estate of the
church of Geneva, and the opinions of Calvin and Theodore Beza
concerning church government, came to affirm, “That none ought
to be esteemed office-bearers in the Church whose titles were not
found in the book of God. And, for the title of bishops, albeit the
same was found in Scripture, yet was it not to be taken in the
sense that the common sort did conceive, there being no
superiority allowed by Christ amongst ministers,”’ &c.
Spottiswoode's History of the Church of Scotland, vol. ii. p. 200.
See also Acts of the General Assemblies, vol. i. p. 331, where it
appears that six bishops were present on this memorable
occasion. The question raised was, ‘Whither if the Bischops, as
they are now in the Kirk of Scotland, hes thair function of the
word of God or not, or if the Chapiter appointit for creating of
them aucht to be tollerated in this reformed Kirk.’ p. 340.
[227] ‘It was ordained, That Bischops and all vthers bearand
Ecclesiasticall functioun, be callit bethair awin names, or
Brethren, in tyme comeing.’ Acts of the General Assemblies of the
Kirk of Scotland, vol. ii. p. 404.
[228] ‘Therfor the Kirk hes concludit, That no Bischops salbe
electit or made heirafter, befor the nixt Generall Assemblie.’ Ibid.
vol. ii. p. 408.
[229] ‘Anent the Act made in the last Assemblie, the 28 of
Aprile 1578, concerning the electioun of Bischops, suspendit quhill
this present Assemblie, and the farther ordour reservit thereto:
The General Assemblie, all in ane voyce, hes concludit, That the
said act salbe extendit for all tymes to come, ay and quhill the
corruptioun of the Estate of Bischops be alluterlie tane away.’
Ibid. vol. ii. p. 413.
[230] ‘Forsameikle as the office of a Bischop, as it is now vsit,
and commounly takin within this realme, hes no sure warrand,
auctoritie, nor good ground out of the (Book and) Scriptures of
God; but is brocht in by the folie and corruptions of (men's)
invention, to the great overthrow of the Kirk of God: The haill
Assemblie of the Kirk, in ane voyce, after libertie givin to all men
to reason in the matter, none opponing themselves in defending
the said pretendit office, Finds and declares the samein pretendit
office, vseit and termeit, as is above said, vnlaufull in the selfe, as
haveand neither fundament, ground nor warrant within the word
of God: and ordaines, that all sick persons as bruiks, or sall bruik
heirafter the said office, salbe chargeit simpliciter to demitt, quyt
and leave of the samein, as ane office quhervnto they are not
callit be God; and siclyke to desist and cease from all preaching,
ministration of the sacraments, or vsing any way the office of
pastors, quhill they receive de novo admission from the Generall
Assemblie, vnder the paine of excommunicatioun to be denuncit
agains them; quherin if they be found dissobedient, or
contraveine this act in any point, the sentence of
excommunicatioun, after dew admonitions, to be execute agains
them.’ Acts of the General Assemblies, vol. ii. p. 453.
[231] As Calderwood triumphantly says, ‘the office of bishops
was damned.’ History of the Kirk, vol. iii. p. 469. ‘Their whole
estat, both the spirituall and civill part, was damned.’ p. 526.
James Melville (Autobiography, p. 52) says that, in consequence
of this achievement, his uncle Andrew ‘gatt the nam of
επισκομαστιξ, Episcoporum exactor, the flinger out of Bischopes.’
[232] Tytler (History of Scotland, vol. vi. p. 302) observes that,
while ‘the great body of the burghers, and middle and lower
classes of the people,’ were Presbyterians, ‘a large proportion of
the nobility supported episcopacy.’ Instead of ‘a large proportion,’
he would not have been far wrong, if he had said ‘all.’ Indeed,
‘Melville himself says the whole peerage was against him.’
Stephen's History of the Church of Scotland, vol. i. p. 269. Forbes
ascribes the aristocratic movement against presbytery to ‘godles
atheists,’ who insisted ‘that there could be nothing so contrair to
the nature of a monarchie,’ &c., ‘than that paritie of authoritie in
pastours.’ Forbes, Certaine Records touching the Estate of the
Kirk, p. 349, edit. Wodrow Society. See also p. 355. ‘That
Democratie (as they called it) whilk allwayes behoved to be full of
sedition and troubble to ane Aristocratie, and so in end to a
Monarchie.’ The reader will observe this important change in the
attitude of classes in Scotland. Formerly, the clergy had been the
allies of the crown against the nobles. Now, the nobles allied
themselves with the crown against the clergy. The clergy, in self-
defence, had to ally themselves with the people.
[233] On the difference between the two productions, there are
some remarks worth looking at, in Argyll's Presbytery Examined,
1848, pp. 38–43. But this writer, though much freer from
prejudice than most Presbyterian authors, is unwilling to admit
how completely the Second Book of Discipline contradicts the
First.
[234] By the Scotch episcopalians.
[235] See the First Book of Discipline, reprinted in the first
volume of A Compendium of the Laws of the Church of Scotland,
2d edit., Edinburgh, 1837. The superintendents were ‘to set,
order, and appoint ministers,’ p. 61; and it would seem (p. 88)
that no minister could be deposed without the consent of his
superintendent; but this could hardly be intended to interfere
with the supreme authority of the General Assembly. See also the
summary, p. 114, where it is said of the superintendents, that ‘in
thair visitatioun thei sal not onlie preiche, but als examine the
doctrine, life, diligence, and behavior of the ministeris, reideris,
elderis, and deaconis.’ According to Spottiswoode (History of the
Church of Scotland, vol. ii. p. 167), ‘the superintendents held their
office during life, and their power was episcopal; for they did
elect and ordain ministers, they presided in synods, and directed
all church censures, neither was any excommunication
pronounced without their warrant.’ See further, on their authority,
Knox's History of the Reformation, vol. ii. p. 161. ‘That
punyschment suld be appointed for suche as dissobeyid or
contemned the superintendentes in thair functioun.’ This was in
1561; and, in 1562, ‘It was ordained, that if ministers be
disobedient to superintendents in anything belonging to
edification, they must be subject to correction.’ Acts of the
General Assemblies of the Kirk, vol. i. p. 14. Compare p. 131: ‘sick
things as superintendents may and aught decyde in their synodall
conventiouns.’
[236] ‘For albeit the Kirk of God be rewlit and governit be Jesus
Christ, who is the onlie King, hie Priest, and Heid thereof, yit he
useis the ministry of men, as the most necessar middis for this
purpose.’ … ‘And to take away all occasion of tyrannie, he willis
that they sould rewl with mutuall consent of brether and equality
of power, every one according to thair functiones.’ Second Book
of Discipline, in A Compendium of the Laws of the Church of
Scotland, vol. i. pp. 126, 127. ‘As to Bischops, if the name
επισκοπος be properly taken, they ar all ane with the ministers, as
befoir was declairit. For it is not a name of superioritie and
lordschip, bot of office and watching.’ p. 142. To understand the
full meaning of this, it should be mentioned, that the
superintendents, established by the Kirk in 1560, not unfrequently
assumed the title of ‘Lordship,’ as an ornament to the extensive
powers conferred upon them. See, for instance, the notes to
Wodrow's Collections upon the Lives of the Reformers of the
Church of Scotland, vol. i. part ii. p. 461. But, in the Second Book
of Discipline, in 1578, the superintendents are, if I rightly
remember, not even once named.
[237] Just as in England, we find that the upper classes are
mostly Episcopalians; their minds being influenced, often
unconsciously, by the, to them, pleasing spectacle of an inequality
of rank, which is conventional, and does not depend upon ability.
On the other hand, the strength of the Dissenters lies among the
middle and lower classes, where energy and intellect are held in
higher respect, and where a contempt naturally arises for a
system, which, at the mere will of the sovereign or minister of the
day, concedes titles and wealth to persons whom nature did not
intend for greatness, but who, to the surprise of their
contemporaries, have greatness thrust upon them. On this
difference of opinion in Scotland, corresponding to the difference
of social position, see the remarks on the seventeenth century, in
Hume's Commentaries on the Law of Scotland, vol. ii. p. 544,
Edinburgh, 1797, 4to.
[238] Record of Privy Council, in M'Crie's Life of Melville, vol. i.
p. 267. ‘The brethrein of Glasgow were charged, under paine of
horning, to admitt Mr. Robert Montgomrie.’ Calderwood's History
of the Kirk, vol. iii. p. 596.
[239] ‘Charges the said Mr. Robert to continue in the ministrie
of the Kirk of Striveling,’ &c. Acts of the General Assemblies, vol.
ii. p. 547. This was in October 1581; the Record of the Privy
Council was in April 1582. Moysie, who was a contemporary, says
that, in March 1581, 2, not only the dean and chapter, but all the
clergy (the ‘haill ministrie’) declared from the pulpit that
Montgomery's appointment ‘had the warrand of the deuill and not
of the word of God, bot wes damnit thairby.’ Moysie's Memoirs,
Edinburgh, 1830, 4to, p. 36.
[240] ‘The title whereof the said duke had procured to him,
that he, having the name of bishop, and eight hundred merks
money for his living and sustentatioun, the whole rents, and other
duteis of the said benefice, might come to the duke's utilitie and
behove.’ Calderwood's History of the Kirk, vol. iv. p. 111. See also
p. 401.
[241] Scot's Apologetical Narration of the State of the Kirk, pp.
24, 25. Calderwood's History of the Kirk, vol. iii. p. 302. Wodrow's
Collections upon the Lives of the Reformers, vol. i. part i. p. 206.
Lyon's History of St. Andrews, vol. i. p. 379. Gibson's History of
Glasgow, p. 59. Hume's History of the House of Douglas, vol. ii.
pp. 216, 217. Chalmers' Caledonia, vol. iii. p. 624.
[242] ‘But the Church passing this point’ (i.e. the simony)
‘made quarrel to him for accepting the bishopric.’ Spottiswoode's
History of the Church of Scotland, vol. ii. p. 282.
[243] Acts of the General Assemblies of the Kirk, vol. ii. p. 548.
[244] ‘A messenger-at-arms entered the house, and charged
the moderator and members of the assembly, on the pain of
rebellion, to desist from the process.’ M'Crie's Life of Melville, vol.
i. p. 268.
[245] ‘The Assemblie and brether present, after voteing in the
said matter, depryvit the said Mr. Robert from all functioun of the
Ministrie in the Kirk of God, dureing the will of the Kirk of God;
and farther, descernit the fearefull sentence of excommunicatioun
to be pronuncit against him in the face of the haill Assemblie, be
the voyce and mouth of the Moderatour present; to the effect,
that, his proud flesh being cast into the hands of Satan, he may
be win againe, if it be possible, to God; and the said sentence
(to) be intimat be every particular minister, at his awin particular
kirk, solemnelie in the first sermoun to be made be them, after
thair returning.’ Acts of the General Assemblies of the Kirk, vol. ii.
p. 562.
[246] Ibid., vol. ii. p. 565. Calderwood (History of the Kirk, vol.
iii. p. 604) says, ‘After long reluctatioun, at lenth he
condescended.’
[247] M'Crie (Life of Melville, vol. i. p. 274) says, ‘In all these
contendings, the ministers had no countenance or support from
any of the nobility.’ It would have been strange if they had, seeing
that the whole movement was essentially democratic.
[248] Melville's Autobiography, p. 129. Calderwood's History of
the Kirk, vol. iii. p. 620. M'Crie's Life of Melville, vol. i. p. 270.
[249] He was seized in August 1582, and was let loose again in
June 1583. Tytler's History of Scotland, vol. vi. pp. 321, 360. It is
a pity that this valuable, and really able, work should be so
superficial in regard to the ecclesiastical affairs of Scotland. Mr.
Tytler appears not to have studied at all the proceedings of the
presbyteries, or even of the General Assemblies; neither does he
display any acquaintance with the theological literature of his
country. And yet, from the year 1560 to about 1700, these
sources disclose more of the genuine history of the Scotch people
than all other sources put together.
[250] ‘The pulpit resounded with applauses of the godly deed.’
Arnot's History of Edinburgh, p. 37.
[251] ‘As he is comming from Leith to Edinburgh, upon Tuisday
the 4th of September, there mett him at the Gallow Greene two
hundreth men of the inhabitants of Edinburgh. Their number still
increased, till he came within the Neather Bow. There they
beganne to sing the 124 Psalme, “Now may Israel say,” &c, and
sang in foure parts, knowne to the most part of the people. They
came up the street till they came to the Great Kirk, singing thus
all the way, to the number of two thowsand. They were muche
moved themselves, and so were all the beholders. The duke was
astonished, and more affrayed at that sight than at anie thing
that ever he had seene before in Scotland, and rave his beard for
anger.’ Calderwood's History of the Kirk, vol. iii. pp. 646, 647.
[252] Acts of the General Assemblies, vol. ii. pp. 595, 596. This
was ordered by the General Assembly which met at Edinburgh on
the 9th of October 1582, p. 585. See also Watson's Historicall
Collections of Ecclesiastick Affairs in Scotland, p. 192, ‘requiring
the ministers in all their churches to commend it unto the people.’
[253] Spottiswoode's History of the Church of Scotland, vol. ii.
p. 308.
[254] James, after his escape, ‘convocat all his peaceabill
Prelatis and Nobles, and thair he notefeit unto thayme the greif
that he consavit of his unlaughfull detentioun the yeir bygayne,
and tharefore desyrit thame to acknawlege the same; and thay
be thair generall voittis decernit the rayd of Ruthven to be
manifest treasoun. The Ministers on the uther part, perswadit the
people that it was a godly fact, and that whasoever wald not
allow thareof in his hart, was not worthie to be estemit a
Christien.’ The Historie of King James the Sext, p. 202, published
by the Bannatyne Club, Edinburgh, 1825, 4to.
[255] ‘Disregard not our threatening; for there was never one
yet in this realm, in the place where your grace is, who prospered
after the ministers began to threaten him.’ Tytler's History of
Scotland, vol. vi. p. 364. See also, in Calderwood's History of the
Kirk, vol. v. pp. 540, 541, a letter from one of the clergy in Fife,
addressed to the king, in 1597. ‘And now, Sir, lett me be free with
you in writting other men's reports, and that of the wisest
politicians. They say, our bygane historeis report, and experience
teacheth, that raro et fere nunquam has a king and a prince
continued long together in this realme; for Filius ante diem
patrios inquirit in annos. And they say, Sir, farther, that
whatsoever they were of your Majestie's predecessors in
governement that oppouned themselves directlie or indirectlie to
God's ordinance in his Kirk, it has beene their wracke and
subversioun in the end. I might herein be more particular; but I
leave it to your Majestie's owne grave and modest consideratioun,
for it concerneth you most neere.’
[256] ‘Saying, “He perverted the laws both of God and man.”’
Spottiswoode's History of the Church of Scotland, vol. ii. p. 309.
Also Tytler's History of Scotland, vol. vi. p. 371.
[257] ‘Mr. Patrick Simson, preaching before the king upon Gen.
iv. 9, “The Lord said to Cain, Where is Abel, thy brother?” said to
the king, before the congregation, “Sir, I assure you, in God's
name, the Lord will ask at you where is the Earl of Moray, your
brother?” The king replyed, before all the congregation, “Mr.
Patrik, my chalmer doore wes never steeked upon you: ye might
have told me anything ye thought in secret.” He replyed, “Sir, the
scandall is publict.”’ Row's History of the Kirk, p. 144. ‘Having
occasion, anno 1593, to preach before the king, he publicly
exhorted him to beware that he drew not the wrath of God upon
himself in patronizing a manifest breach of divine laws.’ Howie's
Biographia Scoticana, p. 120.
[258] ‘Saying, “That Captain James, with his lady Jesabel, and
William Stewart (meaning the colonel), were taken to be the
persecutors of the Church; but that now it was seen to be the
king himself, against whom he denounced the curse that fell on
Jeroboam—that he would die childless, and be the last of his
race.”’ Spottiswoode's History of the Church of Scotland, vol. ii. p.
335.
[259] ‘The king, perceiving by all these letters, that the death
of his mother was determined, called back his ambassadors, and
at home gave order to the ministers to remember her in their
public prayers, which they denied to do.’ … ‘Upon their denial,
charges were directed to command all bishops, ministers, and
other office-bearers in the Church to make mention of her
distress in their public prayers, and commend her to God in the
form appointed. But of all the number only Mr. David Lindsay at
Leith and the king's own ministers gave obedience.’
Spottiswoode's History of the Church, vol. ii. pp. 355, 356. ‘They,
with only one exception, refused to comply.’ Russell's History of
the Church in Scotland, vol. ii. p. 23. Compare Watson's Historicall
Collections of Ecclesiastick Affairs in Scotland, p. 208; and Historie
of James the Sext, p. 225.
[260] ‘They stirred up Mr. John Cowper, a young man not
entered as yet in the function, to take the pulpit before the time,
and exclude the bishop. The king coming at the hour appointed,
and seeing him in the place, called to him from his seat, and said,
“Mr. John, that place is destined for another; yet since you are
there, if you will obey the charge that is given, and remember my
mother in your prayers, you shall go on.” He replying, “that he
would do as the Spirit of God should direct him,” was commanded
to leave the place: and making as though he would stay, the
captain of the guard went to pull him out; whereupon he burst
forth in these speeches: “This day shall be a witness against the
king in the great day of the Lord:” and then denouncing a wo to
the inhabitants of Edinburgh, he went down, and the bishop of
St. Andrews entering the pulpit did perform the duty required.’
Spottiswoode's History of the Church of Scotland, vol. ii. p. 356.
‘The Kingis Majestie, to testifie his earnest and naturall affection
to his mother, causit pray for hir oppinly efter him selff;
quhairvpone arrose a great dissensioun betuix sum of the
ministrie and his Majestie, namely the ministrie of Edinburgh.
Quhairvpone the king appoynted Patrik, archbischop of St.
Androis to teache, bot he wes preuented be Mr. John Covpar
minister, quho come befoir and filled the pulpit. And as the said
Mr. John wes beginnand the prayer, the Kingis Majestie
commandit him to stay: so as Mr. John raschit michtely vpone the
pulpit, saying, “This day sail bear witnes aganis yow in the day of
the lord: woe be to ye Edinburgh, for the last of xi plaiges salbe
the worst.”’ Moysie's Memoirs, p. 59.
[261] See The Historie of King James the Sext, pp. 316–318,
from ‘a just copie of his sermon’ supplied by Ross himself. ‘His
text was upon the 6 chapter of the Prophet Jeremias, verse 28.
“Brethren, we have manie, and almaist innumerable enormiteis in
this cuntrie to be lamentit, as the misgovernement of our king be
sinistrous counsall of sum particular men. They ar all rebellious
traitors, evin the king the maist singular person, and particularlie
everie estait of the land.” … “Our king in sindrie poyntis hes bene
rebellious aganis the Majestie of God.” … “To this howre, we gat
never gude of the Guysien blude, for Queyne Marie his mother
was an oppin persecutor of the sanctis of God, and althoght the
king be not an oppin persecutor, we have had many of his fayre
wordis, wharein he is myghtie aneugh, bot for his gude deiddis, I
commend me to thayme.” … “Admit, that our king be a Christien
king, yit but amen dement, he is a reprobat king. Of all the men
in this nation, the king himself is the maist fynest, and maist
dissembling hypocreit.”’ A very short notice of this sermon is
given by Calderwood (History of the Kirk, vol. v. p. 299), who
probably had not seen the original notes.
[262] The accusation, which was fully proved, was, that ‘he had
publictlie sayd in pulpit, that the papist erles wes come home be
the kingis knavledge and consent, quhairin his Hienes treacherie
wes detectit; that all kingis war deuilis and come of deuilis; that
the deuill wes the head of the court and in the court; that he pray
it for the Queine of Scotland for the faschione, because he saw na
appearance of guid in hir tyme,’ Moysie's Memoirs, p. 128. ‘Having
been heard to affirm, that the popish lords had returned into the
country by the king's permission, and that thereby the king had
discovered the “treacherous hypocrisy of his heart” that “all kings
were the devil's bairns, and that the devil was in the court, and
the guiders of it.” He was proved to have used in his prayer these
indecent words, when speaking of the queen, “We must pray for
her for fashion's sake; but we might as well not, for she will never
do us any good,” He called the queen of England an atheist, and
the Lords of Session bribers; and said that the nobility at large
“were degenerate, godless, dissemblers, and enemies to the
church.”’ Grierson's History of Saint Andrews, p. 30, Cupar, 1838.
Among the charges against him were, ‘Fourthly, that he had
called the queen of England an atheist. Fifthly, that he had
discussed a suspension granted by the lords of session in pulpit,
and called them miscreants and bribers. Sixthly, that, speaking of
the nobility, he said they were “degenerated, godless,
dissemblers, and enemies to the church.” Likewise, speaking of
the council, that he had called them “holiglasses, cormorants, and
men of no religion.”’ Spottiswoode's History of the Church, vol. iii.
p. 21.
[263] See the original papers on ‘The Declinatour of the King
and Counsel's Judicatour in Maters Spirituall, namelie in Preaching
of the Word,’ in Calderwood's History of the Kirk, vol. v. pp. 457–
459, 475–480. Tytler (History of Scotland, vol. vii. pp. 326–332)
has given extracts from them, and made some remarks on their
obvious tendency. See also on the Declinature of Jurisdiction
claimed by the Scotch Church, Hallam's Constitutional History, 4th
edit. 1842, vol. ii. p. 461; and Mackenzie's Laws and Customs of
Scotland in Matters Criminal, Edinburgh, 1699, folio, pp. 181, 182.
[264] M'Crie, in his Life of Melville, vol. ii. pp. 70 seq., has given
an account of the punishment of Black, but, as usual, conceals
the provocation; or, at least, softens it down until it hardly
becomes a provocation. According to him, ‘David Black had been
served with a summons to answer before the privy council for
certain expressions used by him in his sermons.’ Certain
expressions, indeed! But why name the penalty, and suppress the
offence? This learned writer knew perfectly well what Black had
done, and yet all the information bestowed on the reader is a
note at p. 72, containing a mutilated extract from Spottiswoode.
[265] ‘Saying, “He was possessed with a devil; that one devil
being put out, seven worse were entered in place; and that the
subjects might lawfully rise, and take the sword out of his hand:”
which he confirmed by the example of a father that falling into a
frenzy, might be taken by the children and servants of the family,
and tied hand and foot from doing violence.’ Spottiswoode's
History of the Church of Scotland, vol. iii. p. 34. See also Arnot's
History of Edinburgh, pp. 46, 47.
[266] This did not escape the attention of the English
government; and Elizabeth, who was remarkably well informed
respecting Scotch affairs, wrote to James, in 1590, a warning,
which was hardly necessary, but which must have added to his
fears. ‘And lest fayre semblance, that easely may begile, do not
brede your ignorance of suche persons as ether pretend religion
or dissemble deuotion, let me warne you that ther is risen, bothe
in your realme and myne, a secte of perilous consequence, suche
as wold have no kings but a presbitrye, and take our place while
the inioy our privilege, with a shade of Godes word, wiche none is
juged to folow right without by ther censure the be so demed.
Yea, looke we wel unto them.’ Letters of Elizabeth and James VI.,
edited by John Bruce, Camden Society, 1849, 4to, p. 63.
[267] The Reverend James Melville, who was present at the
scene, describes it with exuberant delight. ‘To the quhilk, I
beginning to reply, in my maner, Mr. Andro doucht nocht abyd it,
bot brak af upon the king in sa zealus, powerfull, and unresistable
a maner, that whowbeit the king used his authoritie in maist
crabbit and colerik maner, yit Mr. Andro bure him down, and
outtered the Commission as from the mightie God, calling the
king bot “God's sillie vassall:” and taking him be the sleive,’ &c.
Autobiography and Diary of James Melvill, p. 370. See also
Shields' Hind let loose, 1687, p. 52; and M'Crie's Life of Melville,
vol. ii. p. 66.
[268] In 1593, 4, some of them formed a plot to seize him. See
the evidence from the State-paper Office, in Tytler's History of
Scotland, vol. vii. p. 249, edit. Edinburgh, 1845.
[269] ‘He was the darling hope of the Presbyterian party.’ Ibid.,
vol. vii. p. 410.
[270] ‘Gowry's conspiracy was by them charged on the king, as
a contrivance of his to get rid of that earl.’ Burnet's History of his
own Time, edit. Oxford, 1823, vol. i. p. 31. See also Tytler's
History of Scotland, vol. vii. pp. 439, 440; and on the diffusion of
‘this absurd hallucination,’ see The Spottiswoode Miscellany, vol.
ii. p. 320, Edinburgh, 1845.
[271] See a good note in Pitcairn's Criminal Trials in Scotland,
vol. ii. p. 179, Edinburgh, 1833, 4to. Compare Lawson's Book of
Perth, Edinburgh, 1847, p. xxxix.
[272] Their language, and their general bearing, so enraged
James, as to extort from him a passionate declaration, in 1592,
that ‘it would not be weill till noblemen and gentlemen gott
licence to breake ministers' heads.’ Calderwood's History of the
Kirk, vol. v. p. 148.
[273] ‘At the period of which we speak’ (about the year 1584)
‘the pulpit was, in fact, the only organ by which public opinion
was, or could be, expressed; and the ecclesiastical courts were
the only assemblies in the nation which possessed anything that
was entitled to the name of liberty or independence. Parliament
had its business prepared to its hand, and laid before it in the
shape of acts which required only its assent. Discussion and
freedom of speech were unknown in its meetings. The courts of
justice were dependent on the will of the sovereign, and
frequently had their proceedings regulated, and their decisions
dictated, by letters or messages from the throne. It was the
preachers who first taught the people to express an opinion on
the conduct of their rulers; and the assemblies of the Church set
the earliest example of a regular and firm opposition to the
arbitrary and unconstitutional measures of the court.’ M'Crie's Life
of Melville, vol. i. p. 302.
CHAPTER III.
CONDITION OF SCOTLAND DURING THE SEVENTEENTH AND
EIGHTEENTH CENTURIES.
Scarcely had James mounted the throne of England, when he
began seriously, and on a large scale, to attempt to subjugate the
Scotch Church, which, as he clearly saw, was the principal obstacle
that stood between him and despotic power. While he was merely
King of Scotland, he made several efforts, which were constantly
baffled; but now that he wielded the vast resources of England, the
victory seemed easy.[274] As early as 1584, he had gained a
temporary triumph, by forcing many of the clergy to recognize
episcopacy.[275] But that institution was so repugnant to their
levelling and democratic principles, that nothing could overcome
their abhorrence of it;[276] and, completely overawing the king, they
compelled him to give way, and to retrace his steps. The result was,
that, in 1592, an Act of Parliament was passed, which subverted the
authority of the bishops, and established Presbyterianism; a scheme
based on the idea of equality, and, therefore, suited to the wants of
the Scotch Church.[277]
To this statute, James had assented with the greatest reluctance.
[278] Indeed, his feeling respecting it was so strong, that he
determined, on the first opportunity, to procure its repeal, even if he
used force to effect his purpose. The course he adopted, was
characteristic both of the man and of the age. In December 1596,
one of those popular tumults arose in Edinburgh, which are natural
in barbarous times, and which, under ordinary circumstances, would
have been quelled, and nothing more thought of it.[279] But James
availed himself of this, to strike what he deemed a decisive blow. His
plan was nothing less than to turn into the capital of his own
monarchy, large bodies of armed and licensed banditti, who, by
threatening to plunder the city, should oblige the clergy and their
flocks to agree to whatever terms he chose to dictate. This
magnanimous scheme was well worthy of the mind of James, and it
was strictly executed. From the north, he summoned the Highland
nobles, and from the south, the border barons, who were to be
accompanied by their fierce retainers,—men who lived by pillage,
and whose delight it was to imbrue their hands in blood. At the
express command of James, these ferocious brigands, on the 1st of
January 1597, appeared in the streets of Edinburgh, gloating over
the prospect before them, and ready, when their sovereign gave the
word, to sack the capital, and raze it to the ground.[280] Resistance
was hopeless. Whatever the king demanded, was conceded; and
James supposed that the time was now come, in which he could
firmly establish the authority of the bishops, and, by their aid,
control the clergy, and break their refractory spirit.[281]
In this undertaking, three years were consumed. To insure its
success, the king, supported by the nobles, relied, not only on force,
but also on an artifice, which now seems to have been employed for
the first time. This was, to pack the General Assemblies, by
inundating them with clergymen drawn from the north of Scotland,
where, the old clannish and aristocratic spirit being supreme, the
democratic spirit, found in the south, was unknown. Hitherto, these
northern ministers had rarely attended at the great meetings of the
Church; but James, in 1597, sent Sir Patrick Murray on a special
mission to them, urging them to be present, in order that they might
vote on his side.[282] They, being a very ignorant body, knowing little
or nothing of the questions really at issue, and being, moreover,
accustomed to a state of society in which men, notwithstanding their
lawlessness, paid the most servile obedience to their immediate
superiors, were easily worked upon, and induced to do what they
were bid. By their help, the crown and the nobles so strengthened
their party in the General Assembly, as to obtain in many instances a
majority; and innovations were gradually introduced, calculated to
destroy the democratic character of the Scotch Church.[283]
In 1597, the movement began. From then, until 1600, successive
Assemblies sanctioned different changes, all of which were marked
by that aristocratic tendency which seemed about to carry
everything before it. In 1600, the General Assembly met at
Montrose; and government determined on making a final effort to
compel the Church to establish an episcopal polity. Andrew Melville,
by far the most influential man in the Church, and the leader of the
democratic party, had been elected, as usual, a member of the
Assembly; but the king, arbitrarily interposing, refused to allow him
to take his seat.[284] Still, neither by threats, nor by force, nor by
promises, could the court carry their point. All that they obtained
was, that certain ecclesiastics should be allowed to sit in parliament;
but it was ordered that such persons should every year lay their
commissions at the feet of the General Assembly, and render an
account of their conduct. The Assembly was to have the power of
deposing them; and, to keep them in greater subjection, they were
forbidden to call themselves bishops, but were to be content with
the inferior title of Commissioners of the Church.[285]
After sustaining this repulse, James seems to have been
disheartened; as he made no further effort, though he still laboured
underhand at the restoration of episcopacy.[286] If he had
persevered, it might have cost him his crown. For, his resources
were few; he was extremely poor;[287] and recent events had shown
that the clergy were stronger than he had supposed. When he
thought himself most sure of success, they had subjected him to a
mortifying defeat; and this was the more remarkable, as it was
entirely their own work; they being by this time so completely
separated from the nobles, that they could not rely upon even a
single member of that powerful body.
While affairs were in this state, and while the liberties of Scotland,
of which the Church was the guardian, were trembling in the
balance, Elizabeth died, and the King of Scotland became also King
of England. James at once determined to employ the resources of
his new kingdom to curb his old one. In 1604, that is, only the year
after his accession to the English throne, he aimed a deadly blow at
the Scotch Church, by attacking the independence of their
Assemblies; and, by his own authority, he prorogued the General
Assembly of Aberdeen.[288] In 1605, he again prorogued it; and, to
make his intentions clear, he, this time, refused to fix a day for its
future meeting.[289] Hereupon, some of the ministers, deputed by
presbyteries, took upon themselves to convene it, which they had an
undoubted right to do, as the act of the king was manifestly illegal.
On the day appointed, they met in the session-house of Aberdeen.
They were ordered to disperse. Having, as they conceived, by the
mere fact of assembling, sufficiently asserted their privileges, they
obeyed. But James, now backed by the power of England, resolved
that they should feel the change of his position, and, therefore, of
theirs. In consequence of orders which he sent from London,
fourteen of the clergy were committed to prison.[290] Six of them,
who denied the authority of the privy-council, were indicted for high
treason. They were at once put upon their trial. They were
convicted. And sentence of death was only deferred, that the
pleasure of the king might first be taken, as to whether he would not
be satisfied with some punishment that fell short of sacrificing the
lives of these unhappy men.[291]
Their lives, indeed, were spared; but they were subjected to a
close imprisonment, and then condemned to perpetual exile.[292] In
other parts of the country, similar measures were adopted. Nearly all
over Scotland, numbers of the clergy were either imprisoned or
forced to fly.[293] Terror and proscription were universal. Such was
the panic, that it was generally believed that nothing could prevent
the permanent establishment of despotism, unless there were some
immediate and providential interference on behalf of the Church and
the people.[294]
Nor can it be denied that there were plausible grounds for these
apprehensions. The people had no friends except among the clergy,
and the ablest of the clergy were either in prison or in exile.[295] To
deprive the Church entirely of her leaders, James, in 1606,
summoned to London, Melville and seven of his colleagues, under
pretence of needing their advice.[296] Having got possession of their
persons, he detained them in England.[297] They were forbidden to
return to Scotland; and Melville, who was most feared, was
committed to custody. He was then imprisoned in the Tower, where
he remained four years, and from which he was only liberated on
condition of living abroad, and abandoning altogether his native
country.[298] The seven ministers who had accompanied him to
London were also imprisoned; but, being considered less dangerous
than their leader, they, after a time, were allowed to return home.
The nephew of Melville was, however, ordered not to travel more
than two miles from Newcastle; and his six companions were
confined in different parts of Scotland.[299]
Everything now seemed ripe for the destruction of those ideas of
equality of which, in Scotland, the Church was the sole
representative. In 1610, a General Assembly was held at Glasgow;
and, as the members of it were nominated by the crown,[300]
whatever the government wished was conceded. By their vote,
episcopacy was established, and the authority of the bishops over
the ministers was fully recognized.[301] A little earlier, but in the
same year, two courts of High Commission were erected, one at
Saint Andrews, and one at Glasgow. To them, all ecclesiastical courts
were subordinate. They were armed with such immense power, that
they could cite any one they pleased before them, could examine
him respecting his religious opinions, could have him
excommunicated, and could fine or imprison him, just as they
thought proper.[302] Finally, and to complete the humiliation of
Scotland, the establishment of episcopacy was not considered
complete, until an act was performed, which nothing but its being
very ignominious, could have saved from being ridiculed as an idle
and childish farce. The archbishop of Glasgow, the bishop of Brechin,
and the bishop of Galloway, had to travel all the way to London, in
order that they might be touched by some English bishops.
Incredible as it may appear, it was actually supposed that there was
no power in Scotland sufficiently spiritual to turn a Scotchman into a
prelate. Therefore it was, that the archbishop of Glasgow and his
companions performed what was then an arduous journey to a
strange and distant capital, for the sake of receiving some hidden
virtue, which, on their return home, they might communicate to
their brethren. To the grief and astonishment of their country, these
unworthy priests, abandoning the traditions of their native land, and
forgetting the proud spirit which animated their fathers, consented
to abjure their own independence, to humble themselves before the
English Church, and to submit to mummeries, which, in their hearts,
they must have despised, but which were now inflicted upon them
by their ancient and inveterate foes.[303]
We may easily imagine what would be the future conduct of men,
who, merely for their own aggrandizement, and to please their
prince, could thus renounce the cherished independence of the
Scotch Church. They who crouch to those who are above them
always trample on those who are below them. Directly they returned
to Scotland, they communicated the consecration they had received
in England to their fellow-bishops,[304] who were of the like mould
to themselves, in so far as all of them aided James in his attempt to
subjugate the liberties of their native country. Being now properly
ordained, their spiritual life was complete; it remained for them to
secure the happiness of their temporal life. This they did, by
gradually monopolizing all authority, and treating with unsparing
severity those who opposed them. The fall triumph of the bishops
was reserved for the reign of Charles I., when a number of them
obtained seats in the privy-council, where they behaved with such
overbearing insolence, that even Clarendon, notwithstanding his
notorious partiality for their order, censures their conduct.[305] In the
time, however, of James I., they carried nearly everything before
them.[306] They deprived the towns of their privileges, and forced
them to receive magistrates of their own choosing.[307] They
accumulated wealth, and made an ostentatious display of it; which
was the more disgraceful, as the country was miserably poor, and
their fellow-subjects were starving around them.[308] The Lords of
the Articles, without whose sanction no measure could be presented
to parliament, had been hitherto elected by laymen; but the bishops
now effected a change, by virtue of which the right of nomination
devolved on themselves.[309] Having thus gained possession of the
legislature, they obtained the enactment of fresh penalties against
their countrymen. Great numbers of the clergy they suspended;
others they deprived of their benefices; others they imprisoned. The
city of Edinburgh, being opposed to the rites and ceremonies lately
introduced, and being, like the rest of the country, hostile to
episcopacy, the bishops fell on it also, displaced several of its
magistrates, seized some of the principal citizens, and threatened to
deprive it of the courts of justice, and of the honour of being the
seat of government.[310]
In the midst of all this, and while things seemed to be at their
worst, a great reaction was preparing. And the explanation of the
reaction is to be found in that vast and pregnant principle, on which
I have often insisted, but which our common historians are unable to
understand; namely, that a bad government, bad laws, or laws badly
administered, are, indeed, extremely injurious at the time, but can
produce no permanent mischief; in other words, they may harm a
country, but can never ruin it. As long as the people are sound, there
is life, and while there is life, there will be reaction. In such case,
tyranny provokes rebellion, and despotism causes freedom. But if
the people are unsound, all hope is gone, and the nation perishes.
In both instances, government is, in the long run, inoperative, and is
nowise responsible for the ultimate result. The ruling classes have,
for the moment, immense power, which they invariably abuse,
except when they are restrained, either by fear, or by shame. The
people may inspire them with fear; public opinion may inspire them
with shame. But whether or not that shall happen, depends on the
spirit of the people, and on the state of opinion. These two
circumstances are themselves governed by a long chain of
antecedents, stretching back to a period, always very distant, and
sometimes so remote as to baffle observation. When the evidence is
sufficiently abundant, those antecedents may be generalized; and
their generalization conducts us to certain large and powerful
causes, on which the whole movement depends. In short periods,
the operation of these causes is imperceptible, but in long periods, it
is conspicuous and supreme; it colours the national character; it
controls the great sweep and average of affairs. In Scotland, as I
have already shown, general causes made the people love their
clergy, and made the clergy love liberty. As long as these two facts
coëxisted, the destiny of the nation was safe. It might be injured,
insulted, and trampled upon. It might be harmed in various ways;
but the greater the harm, the surer the remedy, because the higher
the spirit of the country would be roused. All that was needed was, a
little more time, and a little more provocation. We, who, standing at
a distance, can contemplate these matters from an elevation, and
see how events pressed on and thickened, cannot mistake the
regularity of their sequence. Notwithstanding the apparent
confusion, all was orderly and methodical. To us, the scheme is
revealed. There is the fabric, and it is of one hue, and one make.
The pattern is plainly marked, and fortunately it was worked into a
texture, whose mighty web was not to be broken, either by the arts,
or the violence, of designing men.
It was, therefore, of no avail that tyranny did her utmost. It was of
no avail that the throne was occupied by a despotic and
unscrupulous king, who was succeeded by another, more despotic
and more unscrupulous than himself. It was of no avail that a
handful of meddling and intrusive bishops, deriving their
consecration from London, and supported by the authority of the
English church, took counsel together, and conspired against the
liberties of their native land. They played the part of spies and of
traitors, but they played it in vain. Yet, everything that government
could give them, it gave. They had the law on their side, and they
had the right of administering the law. They were legislators,
councillors, and judges. They had wealth; they had high-sounding
titles; they had all the pomp and attributes for which they bartered
their independence, and with which they hoped to dazzle the eyes of
the vulgar. Still, they could not turn back the stream; they could not
even stop it; they could not prevent it from coming on, and
swallowing them up in its course. Before that generation passed
away, these little men, big though they were in their own conceit,
succumbed, and fell. The hand of the age was upon them, and they
were unable to resist. They were struck down, and humbled; they
were stripped of their offices, their honours, and their splendour:
they lost all which minds like theirs hold most dear. Their fate is an
instructive lesson. It is a lesson, both to the rulers of nations, and to
those who write the history of nations. To rulers, in so far as it is one
of many proofs how little they can do, and how insignificant is the
part which they play in the great drama of the world. To historians,
the result should be especially instructive, as convincing them that
the events on which they concentrate their attention, and which they
believe to be of supreme importance, are in reality of trifling value,
and, so far from holding the first rank, ought to be made subservient
to those large and comprehensive studies, by whose aid alone, we
can ascertain the conditions which determine the tread and destiny
of nations.
The events that now happened in Scotland, may be quickly told.
The patience of the country was well-nigh exhausted, and the day of
reckoning was at hand.[311] In 1637, the people began to rise. In
the summer of that year, the first great riot broke out in Edinburgh.
[312] The flame quickly spread, and nothing could stop it. By
October, the whole nation was up, and an accusation was preferred
against the bishops, which was signed by nearly every corporation,
and by men of all ranks.[313] In November, the Scotch, in defiance of
the Crown, organized a system of representation of their own, in
which every class had a share.[314] Early in 1638, the National
Covenant was framed; and the eagerness with which it was sworn
to, showed that the people were determined, at all hazards, to
vindicate their rights.[315] It was now evident that all was over.
During the summer of 1638, preparations were made, and, in the
autumn, the storm broke. In November, the first General Assembly
seen in Scotland for twenty years, met at Glasgow.[316] The Marquis
of Hamilton, the king's commissioner, ordered the members to
separate.[317] They refused.[318] Nor would they disband, until they
had done the work expected from them.[319] By their vote, the
democratic institution of presbyteries was restored to its old power;
the forms of consecration were done away with; the bishops were
degraded from their functions, and episcopacy was abolished.[320]
Thus, the bishops fell, even more rapidly than they had risen.[321]
As, however, their fall was merely a part of the democratic
movement, matters could not stop there.[322] Scarcely had the
Scotch expelled their bishops, when they made war upon their king.
In 1639, they took up arms against Charles. In 1640, they invaded
England. In 1641, the king, with the hope of appeasing them, visited
Scotland, and agreed to most of their demands. It was too late. The
people were hot, and a cry for blood had gone forth. War again
broke out. The Scotch united with the English, and Charles was
every where defeated. As a last chance, he threw himself upon the
mercy of his northern subjects,[323] But his offences were of that
rank and luxuriant growth, that it was impossible to forgive them.
Indeed, the Scotch, instead of pardoning him, turned him to profit.
He had not only trampled on their liberties, he had also put them to
an enormous expense. For the injury, he could offer no adequate
atonement; but the expense they had incurred, might be defrayed.
And as it is an old and recognized maxim, that he who cannot pay
with his purse, shall pay with his body, the Scotch saw no reason
why they should not derive some advantage from the person of their
sovereign, particularly as, hitherto, he had caused them nothing but
loss and annoyance. They, therefore, gave him up to the English,
and, in return, received a large sum of money, which they claimed as
arrears due to them for the cost of making war on him.[324] By this
arrangement, both of the contracting parties benefited. The Scotch,
being very poor, obtained what they most lacked. The English, a
wealthy people, had indeed to pay the money, but they were
recompensed by getting hold of their oppressor, against whom they
thirsted for revenge; and they took good care never to let him loose,
until they had exacted the last penalty of his great and manifold
crimes.[325]
After the execution of Charles I., the Scotch recognized his son as
his successor. But before they would crown the new king, they
subjected him to a treatment which hereditary sovereigns are not
much accustomed to receive. They made him sign a public
declaration, expressing his regret for what had happened, and
acknowledging that his father, moved by evil counsels, had unjustly
shed the blood of his subjects. He was also obliged to declare, that
by these things he felt humbled in spirit. He had, moreover, to
apologize for his own errors, which he ascribed partly to his
inexperience, and partly to the badness of his education.[326] To
evince the sincerity of this confession, and in order that the
confession might be generally known, he was commanded to keep a
day of fasting and humiliation, in which the whole nation would
weep and pray for him, in the hope that he might escape the
consequences of the sins committed by his family.[327]
The spirit, of which acts like these are but symptoms, continued to
animate the Scotch during the rest of the seventeenth century. And
fortunately for them it did so. For, the reigns of Charles II. and
James II. were but repetitions of the reigns of James I. and Charles
I. From 1660 to 1688, Scotland was again subjected to a tyranny, so
cruel, and so exhausting, that it would have broken the energy of
almost any other nation.[328] The nobles, whose power had been
slowly but constantly declining,[329] were unable to resist the
English, with whom, indeed, they rather seemed willing to combine,
in order that they might have a share in plundering and oppressing
their own country.[330] In this, the most unhappy period through
which Scotland had passed since the fourteenth century, the
government was extremely powerful; the upper classes, crouching
before it, thought only of securing their own safety; the judges were
so corrupt, that justice, instead of being badly administered, was not
administered at all;[331] and the parliament, completely overawed,
consented to what was termed the recissory act, by which, at a
single stroke, all laws were repealed which had been enacted since
1633; it being considered that those twenty-eight years formed an
epoch of which the memory should, if possible, be effaced.[332]
But, though the higher ranks ignominiously deserted their post,
and destroyed the laws which upheld the liberties of Scotland, the
result proved that the liberties themselves were indestructible. This
was because the spirit remained, by which the liberties had been
won. The nation was sound at the core; and while that was the
case, legislators could, indeed, abolish the external manifestations of
freedom, but could by no means touch the causes on which the
freedom depended. Liberty was prostrate, but yet it lived. And the
time would surely come, when a people, who loved it so dearly,
would vindicate their rights. The time would come, when, in the
words of the great poet of English liberty, the nation would rouse
herself like a strong man after sleep, and, shaking her invincible
locks, would be as an eagle muing her mighty youth, kindling her
undazzled eyes at the midday beam, and purging and unscaling her
sight at the heavenly fountain; while the timorous birds of her evil
destiny, loving the twilight, should flutter about, amazed at what she
meant.
Still, the crisis was sad and dangerous. The people, deserted by
every one except their clergy, were ruthlessly plundered, murdered,
and hunted, like wild-beasts, from place to place. From the tyranny
of the bishops, they had so recently smarted, that they abhorred
episcopacy more than ever; and yet that institution was not only
forced upon them, but government put at its head Sharp, a cruel
and rapacious man, who, in 1661, was raised to the archbishopric of
St. Andrews.[333] He set up a court of ecclesiastical commission,
which filled the prisons to overflowing; and when they would hold no
more, the victims were transported to Barbadoes, and other
unhealthy settlements.[334] The people, being determined not to
submit to the dictation of government respecting their religious
worship, met together in private houses; and, when that was
declared illegal, they fled from their houses to the fields. But there,
too, the bishops were upon them.[335] Lauderdale, who, for many
years, was at the head of affairs, was greatly influenced by the new
prelates, and aided them with the authority of the executive.[336]
Under their united auspices, a new contrivance was hit upon; and a
body of soldiers, commanded by Turner, a drunken and ferocious
soldier, was let loose upon the people.[337] The sufferers, galled to
madness, rose in arms. This was made the pretence, in 1667, for
fresh military executions, by which some of the fairest parts of
western Scotland were devastated, houses burned, men tortured,
women ravished.[338] In 1670, an act of parliament was passed,
declaring that whoever preached in the fields without permission
should be put to death.[339] Some lawyers were found bold enough
to defend innocent men, when they were tried for their lives; it was
therefore determined to silence them also, and, in 1674, a great part
of the Faculty of Advocates was expelled from Edinburgh.[340] In
1678, by the express command of government, the Highlanders
were brought down from their mountains, and, during three months,
were encouraged to slay, plunder, and burn at their pleasure, the
inhabitants of the most populous and industrious parts of Scotland.
For centuries, the bitterest animosity had existed between the
Highlanders and Lowlanders; and now these savage mountaineers
were called from their homes, that they might take full revenge. And
well they glutted their ire. During three months, they enjoyed every
license. Eight thousand[341] armed Highlanders, invited by the
English government, and receiving beforehand an indemnity for
every excess,[342] were left to work their will upon the towns and
villages of Western Scotland. They spared neither age nor sex. They
deprived the people of their property; they even stripped them of
their clothes, and sent them out naked to die in the fields. Upon
many, they inflicted the most horrible tortures. Children, torn from
their mothers, were foully abused; while both mothers and
daughters were subjected to a fate, compared to which death would
have been a joyful alternative.[343]
It was in this way, that the English government sought to break
the spirit, and to change the opinions, of the Scotch people. The
nobles looked on in silence, and, so far from resisting, had not even
the courage to remonstrate. The parliament was equally servile, and
sanctioned whatever the government demanded. Still, the people
were firm. Their clergy, drawn from the middle classes, clung to
them; they clung to their clergy, and both were unchanged. The
bishops were hated as allies of the government, and were with
reason regarded as public enemies. They were known to have
favoured, and often to have suggested, the atrocities which had
been committed;[344] and they were so pleased with the punishment
inflicted upon their opponents, that no one was surprised, when, a
few years later, they, in an address to James II., the most cruel of all
the Stuarts, declared that he was the darling of heaven, and hoped
that God might give him the hearts of his subjects, and the necks of
his enemies.[345]
The character of the prince, whom the bishops thus delighted to
honour, is now well understood. Horrible as were the crimes which
had been perpetrated, they were surpassed by what occurred, when
he, in 1680, assumed the direction of affairs.[346] He had worked
himself to that pitch of iniquity, as to derive actual enjoyment from
witnessing the agonies of his fellow-creatures. This is an abyss of
wickedness, into which even the most corrupt natures rarely fall.
There have been, and always will be, many men who care nothing
for human suffering, and who will inflict any amount of pain, in order
to gain certain ends. But to take delight in the spectacle, is a
peculiar and hideous abomination. James, however, was so dead to
shame, that he did not care even to conceal his horrible tastes.
Whenever torture was inflicted, he was sure to be present, feasting
his eyes, and revelling with a fiendish joy.[347] It makes our flesh
creep to think that such a man should have been the ruler of
millions. But what shall we say to the Scotch bishops, who
applauded him, of whose conduct they were daily witnesses? Where
can we find language strong enough to stigmatize those recreant
priests, who, having passed years in attempting to subjugate the
liberties of their country, did, towards the close of their career, and
just before their final fall, band together, and employ their united
authority, as ministers of a holy and peaceful religion, to stamp with
public approval, a prince, whose malignant cruelty made him loathed
by his contemporaries, and whose revolting predilections, unless we
ascribe them to a diseased brain, are not only a slur upon the age
which tolerated them, but a disgrace to the higher instincts of our
common nature?
So utterly corrupt, however, were the ruling classes in Scotland,
that such crimes seem hardly to have excited indignation. The
sufferers were refractory subjects, and against them every thing was
lawful. The usual torture, which was called the torture of the boots,
was to place the leg in a frame, into which wedges were driven, until
the bones were broken.[348] But when James visited Scotland, an
opinion began to grow up, that this was too lenient, and that other
means must be devised. The spirit which he communicated to his
subordinates, animated his immediate successors, and, in 1684,
during his absence, a new instrument was introduced, termed the
thumbikins. This was composed of small steel screws, arranged with
such diabolical art, that not only the thumb, but also the whole
hand, could be compressed by them, producing pain more exquisite
than any hitherto known, and having, moreover, the advantage of
not endangering life; so that the torture could be frequently
repeated on the same person.[349]
After this, little more need be said.[350] From the mere mention of
such things, the mind recoils with disgust. The reader of the history
of that time sickens and faints at the contrivances by which these
Welcome to our website – the ideal destination for book lovers and
knowledge seekers. With a mission to inspire endlessly, we offer a
vast collection of books, ranging from classic literary works to
specialized publications, self-development books, and children's
literature. Each book is a new journey of discovery, expanding
knowledge and enriching the soul of the reade

Our website is not just a platform for buying books, but a bridge
connecting readers to the timeless values of culture and wisdom. With
an elegant, user-friendly interface and an intelligent search system,
we are committed to providing a quick and convenient shopping
experience. Additionally, our special promotions and home delivery
services ensure that you save time and fully enjoy the joy of reading.

Let us accompany you on the journey of exploring knowledge and


personal growth!

ebookname.com

You might also like