(Ebook) Essential Algorithms : a Practical Approach to Computer Algorithms by Rod Stephens ISBN 9781118612101, 9781118612767, 9781118797297, 9781299759992, 1118612108, 1118612760, 1118797299, 1299759998 instant download
(Ebook) Essential Algorithms : a Practical Approach to Computer Algorithms by Rod Stephens ISBN 9781118612101, 9781118612767, 9781118797297, 9781299759992, 1118612108, 1118612760, 1118797299, 1299759998 instant download
https://ebooknice.com/product/essential-algorithms-31030430
https://ebooknice.com/product/biota-grow-2c-gather-2c-cook-6661374
https://ebooknice.com/product/essential-algorithms-a-practical-
approach-to-computer-algorithms-4543036
https://ebooknice.com/product/matematik-5000-kurs-2c-larobok-23848312
(Ebook) SAT II Success MATH 1C and 2C 2002 (Peterson's SAT II Success)
by Peterson's ISBN 9780768906677, 0768906679
https://ebooknice.com/product/sat-ii-success-
math-1c-and-2c-2002-peterson-s-sat-ii-success-1722018
(Ebook) Master SAT II Math 1c and 2c 4th ed (Arco Master the SAT
Subject Test: Math Levels 1 & 2) by Arco ISBN 9780768923049,
0768923042
https://ebooknice.com/product/master-sat-ii-math-1c-and-2c-4th-ed-
arco-master-the-sat-subject-test-math-levels-1-2-2326094
https://ebooknice.com/product/cambridge-igcse-and-o-level-history-
workbook-2c-depth-study-the-united-states-1919-41-2nd-edition-53538044
https://ebooknice.com/product/essential-algorithms-a-practical-
approach-to-computer-algorithms-using-python-and-c-12274474
https://ebooknice.com/product/essential-algorithms-a-practical-
approach-to-computer-algorithms-using-python-and-c-second-
edition-57280052
bindex.indd 05:47:54:PM 07/10/2013 Page 602
Essential Algorithms
A Practical Approach to Computer
Algorithms
Rod Stephens
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)
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.
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.
iii
iv
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.)
Introduction xv
Glossary 559
Index 573
vi
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
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
Glossary 559
Index 573
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.
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!
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.
Exploring the Variety of Random
Documents with Different Content
"We then presented the King with two arzies (petitions), desiring he
would grant to Nujm-u-Dowlah the Nizamut of Bengal, Bahar, and
Orissa, and to the Company, the Dewanny of the same provinces; to
both of which His Majesty has signed his fiat, and the proper
instruments for both are now drawing out."
The King, at the same time, granted firmans confirming to the
Company for ever all the lands round Madras and elsewhere
assigned to them by the Nabob of Arcot; as well as a free gift of the
five northern Circars. This was the first formal grant or confirmation
by the King to the Company, of these territories. The grant of Lord
Clive's jaghire, to the Company, was likewise confirmed.
The King was eager to induce Clive to march to Delhi and replace
him on the throne. But this was steadily refused. Clive's policy was
to interpose a friendly native power between our territories and the
Afghans, and as far as possible the Mahrattas. He saw that the King,
from his weak character and large pretensions was quite unfit for
such a purpose; and that none was so proper, both from character
and power, as Sujah-u-Dowlah. This was one cause why he was
anxious to have strengthened him, by restoring Corah. He wished to
induce the King to reside quietly in the Company's territories; but
finding this impracticable, gave him to understand that the Company
could not join him as a party in any of his ambitious enterprises,
beyond the limits of their own territories.
Such was the conclusion of these important negotiations, by which
the English East India Company became the real sovereigns of
Bengal, Bahar, Orissa, and other extensive territories. In these
provinces they now stood in the place of the Nabobs, and had
gained a right to levy and dispose of the whole revenues under
some very moderate burthens. They were no longer dependent on
the regularity of native princes for the payment of their troops, or
support of their establishments. The Nabob of Bengal was become a
puppet in their hands, of little use, but as a cover to their dealings
with European powers. Clive estimates the annual clear gain to the
Company, including their former possessions of Burdwan, &c., and
after paying the King, the Nabob, and all other expenses, as not
short of 122 lacs, or 1,650,000l.[94]
Clive had received from the King, in 1758, a sunnud appointing him
to the high rank of a munsubdar of six thousand foot, and of five
thousand horse, with the title of Zubdit-al-mulk, Nazir-ed-Dowla,
Sabat Jung, Behader.[95] The title of Sabat Jung he had originally, as
already mentioned, received from the Nabob of Arcot, for his gallant
exploits in that prince's service, and by that title he always continued
to be known in Bengal. He now received some augmentation of
sounding titles, but what they were does not appear.
While Clive was engaged in these public duties he did not intermit in
the regularity of his correspondence with his friends in England.
Some extracts from his letters will show the light in which he
considered his own situation and transactions.
[96][The following letter[97] to Mr. Salvadore, whom he employed as
a man of business, merits to be preserved as a proof of Clive's
disinterested conduct during this his last period of service in India:—
"I return you many thanks for your obliging letter, and for the very
favourable opinion you are pleased to entertain of my abilities, as
well as disposition to do my duty to the Company. It must be my
own fault if I do not answer the expectations of all the real and
disinterested proprietors; as for the occasional ones, and those who
act from resentment and selfish principles, I hold them in too much
contempt to cast away one thought about them.
"If I was to dwell upon the situation of the Company's affairs in
Bengal, both civil and military, a volume would not be sufficient.
However, I have the satisfaction of informing you, that I have
already made a great progress towards reforming those enormous
abuses of power, which cry aloud for redress. The inhabitants have
been laid under contribution by both civil and military, their goods
taken from them at an under price, and presents of money have
either been extorted from them, or given for interfering in the affairs
of government by insisting on men of high employments being
turned out, and others appointed in their room. The gentlemen
having the revenues of the country, amounting to upwards of
3,000,000l. per annum at their command, were making such hasty
strides towards independency, that in two years' time I am
persuaded the Company would not have had one servant upon this
establishment above the rank of a writer. In short, if the Directors do
not behave with spirit and integrity, and the Proprietors lay aside
their animosities, they will become answerable to the nation and to
Parliament, for being the cause of losing the greatest advantages
which ever have happened to England since it has been a nation.
"As for myself, although tempted on all sides by offers of riches
without bounds, I have refused every thing; and I am the greatest
villain upon earth, if either I or any one dependent upon or
belonging to me, with my knowledge, either directly or indirectly,
benefit ourselves the value of one farthing, except what shall be
specified in an account current which I intend laying before the
Directors, upon my arrival in England. Indeed, if I suffered myself to
be corrupted, I could not with any face undertake (in conjunction
with the Committee who have heartily and unanimously joined me)
the reformations which are essentially necessary for the Company's
welfare.
"The King has granted to the Company for ever, with the
approbation and consent of the Nabob, all the revenues which shall
remain after paying him a certain tribute, and allowing a sum
sufficient for the dignity and support of the Nabob. The Company's
income exceeds 2,000,000l. sterling per annum, and their civil and
military expenses in future never shall exceed 700,000l. per annum,
in time of peace, and 1,000,000l. in time of war. For further
particulars, let me refer you to Mr. Walsh. With regard to the French
forces, I shall put those of the Company upon so respectable a
footing, that all the powers of Europe can have no chance of
succeeding, without first landing, and being supported by the
powers of the country; and that appears very impracticable, since I
have lately acquired a grant from the King of five northern
provinces, those the French formerly possessed."
Clive's correspondence with his historian Orme appears at this period
to have revived, and he evidently looks to him as the transmitter of
his fame to posterity[98]:—
"I have wrote so many letters, and gone through such a scene of
public business, that I cannot attempt describing to you any part of
our proceedings in this part of the world. Scrafton, Walsh, and
Colonel Smith will furnish you with abundant matter of surprize and
astonishment. Let it suffice to say, that fortune seems determined to
accompany me to the last; every object, every sanguine wish, is
upon the point of being completely fulfilled, and I am arrived at the
pinnacle of all I covet, by affirming the Company shall, in spite of all
envy, malice, faction, and resentment, acknowledge they are
become the most opulent company in the world, by the battle of
Plassey; and Sir Hannibal Hotpot shall acknowledge the same.
"I am preparing plans in abundance for you. You shall have very
exact charts of Bengal, Bahar, and Orissa, and of the Mogul empire
as far as Delhi at least. A map of the Ganges likewise, and all the
other rivers of consequence."
The following letters to his cousin Harry and to his father are
pleasing proofs that his important occupations never cooled his mind
from his duties and feelings as a relation or a friend:—
"I have received[99] your letter of 22d of November, 1764, by which
I find you are all in health, though not so happy as when I was
among you. I make no doubt of once more contributing towards that
happiness, though not quite so soon as I expected, when in
England, owing to the length of our passage. I have pitched upon
the beginning of December, 1766, for resigning this government;
and nothing but my death shall prevent it. General Carnac, myself,
and the rest of our family, propose coming most of the way
overland; and shall, in all probability, be in London some time in
April, 1767.
"I have been seven hundred miles up the country, and have
established a firm and lasting peace, I hope, with the Great Mogul
and his vizier, Shuja Dowlah. I have seen much of his Majesty, and
he has appointed me one of his first omrahs, or nobles, of his
empire, with an immense title, not worth sixpence in England.
Touching all these matters, I must refer you to Mr. Walsh.
"I am glad you have put a stop to Stycke expenses: they became
enormous, and it will be time enough to go on with them upon my
arrival in England; but I approve greatly of your repairing Walcot,
and making it fit for Lady Clive's reception. The only concern I feel
arises from a conviction of what she must suffer from so long an
absence.
"With regard to myself, I have full employment, and enjoy my health
rather better than in England, though I find I cannot bear the heat
so well as formerly, which makes me determined to quit the country
as soon as possible."
"I rejoice," he writes[100] to his father, "to hear from others, though
not from yourself, that, notwithstanding the accident which has
happened to one of your eyes, you retain both your spirits, appetite,
and health. It is impossible, without a miracle, to enjoy the blessings
of life in that perfection in our latter days as in the days of youth;
but I really think your temperance and the goodness of your
constitution will carry you through life with ease and satisfaction to
yourself to an age nearly equal to that of your aunt Judy.
"Although I enjoy better health than in England, India is by no
means agreeable to me, separated as I am from my wife, children,
and dearest relations. The length of our passage will make my
absence one year more than I intended, but this you may be
assured of, that nothing shall detain me in Bengal beyond the
beginning of December, 1766; and I hope to see you all in good
health and spirits, some time in April, 1767.
"I have been seven hundred miles up the country, and have been
very conversant with His Majesty, the Great Mogul. He has made me
one of the first omrahs, or nobles, of his empire. I have concluded a
peace for the Company, which I hope will last, and obtained from
the King a grant of a revenue of 2,000,000l. sterling per annum for
them for ever; and, what is more, I have put them on a way of
securing this immense revenue, in such a manner that it is almost
impossible to deprive the Company of it, at least for some years to
come.
"With regard to myself, I have not benefited, or added to my fortune
one farthing, nor shall I; though I might, by this time, have received
500,000l. sterling. What trifling emoluments I cannot avoid receiving
shall be bestowed on Maskelyne, Ingham, and Strachey, as a reward
for their services and constant attention upon my person. I am much
obliged to the Doctor for his care of my health: he is worth about
2000l. already. This ship, sent express, will bring the Company the
most important news they ever received; and, if they are not
satisfied with mine and the Committee's conduct, I will pronounce
there is not one grain of honour or integrity remaining in England.
The reformation I am making, in both the civil and military branches,
will render the acquisition of fortunes not so sudden, or certain, as
formerly. This, added to the shortness of my stay in India, induces
me to think Captain Sempill had better stay in England, where we
may serve him by our interest at home. Remember me in the most
affectionate manner to my mother. She has acted a great part in life.
The uniformity of her conduct with regard to her children must, at
the same time it affords her the most pleasing reflections, influence
them to entertain the highest respect and veneration for so
deserving a parent. I will most certainly write to her, and to my
brothers and sisters, who have my most affectionate wishes."
In numerous other private letters he dwells upon the same subject.]
[101]
CHAP. XVII.
LORD CLIVE landed at Portsmouth on the 14th of July, 1767, and
reached London on the following day. Though the sea-voyage
probably preserved his life, it still left his constitution very much
shattered; and, on his arrival in London, his physicians immediately
recommended that he should repair to Bath, for the purpose of
drinking the waters. He remained in town, therefore, only a few days
to be presented to their Majesties, to whom he had brought letters
and presents from the Nabob of Arcot; and, in the first days of
August, he set out for Bath, taking in his way Wotton, the seat of his
friend Mr. George Grenville. His disorder was a severe bilious
complaint, attended with spasms, loss of appetite, and indigestion; a
continuation or consequence of that derangement of the liver from
which he had already suffered so much in Bengal.
On his arrival, he was warmly welcomed, not only by his family and
numerous private friends, but by the men most distinguished for
rank and talent in England, and by the Court of Directors, who owed
him so much. While conducting the affairs of his country with such
distinguished honour and success in India, he had not been
forgotten in Europe, where his name occupied a high rank among
those of the illustrious men, who had raised the fame of England to
so high an eminence at that glorious period. His statue, with those
of Admiral Sir George Pocock, and of General Lawrence, had been
placed in the India House.[130] The first part of Orme's "History of
the Military Transactions of the British Nation in Indostan," had
appeared in 1763, and had spread the renown of the hero of the
story wherever the English language is read. When Clive, during his
second government, had enlarged so much his own fame, and the
fame and power of his country, he felt a natural desire that the
elegant historian should continue his work, and commemorate these
great events; and accordingly he furnished him with all the materials
that he possessed for aiding his progress. "What think you," says he,
with a just pride, in a letter to Orme, "of closing the third volume of
your history with an account of the King (of Delhi's) being at last
placed in a situation of affluence and grandeur, the Vizier Sujah-u-
Dowlah being obliged to sue for peace, which was granted upon
very honourable terms, and the Company being in possession of the
revenues of Bengal, Bahar, and Orissa, amounting to 4,000,000l.
sterling per annum, and the country in a state of perfect
tranquillity?"[131] The subject was a fine one, every way worthy of
the historian's talents; and the proposed enlargement would have
given a suitable close and unity to his former labours. But Orme did
not delight in bold and rapid sketches; and the perhaps excessive
detail in which he indulged in his most interesting historical work,
prevented him from at all entering on the history of these
memorable transactions; so that, at the close of his third volume, he
had not advanced beyond the year 1760, the time when Clive left
the country after his first government. At the same time, it is not to
be supposed that Clive escaped a large share of that envy, and of
the consequent abuse, that generally attend the triumph of a
fortunate commander. The many enemies whom he had made, filled
the public papers, to a more than ordinary degree, with acrimonious
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.
ebooknice.com