Download ebooks file Data Structures and Algorithms with JavaScript 1st Edition Michael Mcmillan all chapters
Download ebooks file Data Structures and Algorithms with JavaScript 1st Edition Michael Mcmillan all chapters
com
https://ebookname.com/product/data-structures-and-
algorithms-with-javascript-1st-edition-michael-mcmillan/
OR CLICK HERE
DOWLOAD NOW
https://ebookname.com/product/data-structures-and-algorithms-in-c-2nd-
edition-michael-t-goodrich/
ebookname.com
https://ebookname.com/product/problem-solving-with-algorithms-and-
data-structures-using-python-second-edition-bradley-n-miller/
ebookname.com
https://ebookname.com/product/david-griffiths-and-the-missionary-
history-of-madagascar-1-edition-gwyn-campbell/
ebookname.com
Discrete Time Branching Processes in Random Environment
1st Edition Götz Kersting
https://ebookname.com/product/discrete-time-branching-processes-in-
random-environment-1st-edition-gotz-kersting/
ebookname.com
https://ebookname.com/product/a-playful-path-bernard-de-koven/
ebookname.com
https://ebookname.com/product/music-in-words-trevor-herbert/
ebookname.com
https://ebookname.com/product/c-programming-program-design-including-
data-structures-fourth-edition-d-s-malik/
ebookname.com
https://ebookname.com/product/water-infrastructure-issues-1st-edition-
james-d-haffner/
ebookname.com
Equine Dermatology 1st Edition Danny W. Scott Dvm Dacvd
https://ebookname.com/product/equine-dermatology-1st-edition-danny-w-
scott-dvm-dacvd/
ebookname.com
www.it-ebooks.info
www.it-ebooks.info
Data Structures and Algorithms
with JavaScript
Michael McMillan
www.it-ebooks.info
Data Structures and Algorithms with JavaScript
by Michael McMillan
Copyright © 2014 Michael McMillan. All rights reserved.
Printed in the United States of America.
Published by O’Reilly Media, Inc., 1005 Gravenstein Highway North, Sebastopol, CA 95472.
O’Reilly books may be purchased for educational, business, or sales promotional use. Online editions are
also available for most titles (http://my.safaribooksonline.com). For more information, contact our corporate/
institutional sales department: 800-998-9938 or corporate@oreilly.com.
Editors: Brian MacDonald and Meghan Blanchette Cover Designer: Karen Montgomery
Production Editor: Melanie Yarbrough Interior Designer: David Futato
Copyeditor: Becca Freed Illustrators: Rebecca Demarest and Cynthia Clarke
Proofreader: Amanda Kersey Fehrenbach
Indexer: Ellen Troutman-Zaig
Nutshell Handbook, the Nutshell Handbook logo, and the O’Reilly logo are registered trademarks of O’Reilly
Media, Inc. Data Structures and Algorithms with JavaScript, the image of an amur hedgehog, and related
trade dress are trademarks of O’Reilly Media, Inc.
Many of the designations used by manufacturers and sellers to distinguish their products are claimed as
trademarks. Where those designations appear in this book, and O’Reilly Media, Inc. was aware of a trademark
claim, the designations have been printed in caps or initial caps.
While every precaution has been taken in the preparation of this book, the publisher and authors assume
no responsibility for errors or omissions, or for damages resulting from the use of the information contained
herein.
ISBN: 978-1-449-36493-9
[LSI]
www.it-ebooks.info
Table of Contents
Preface. . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . ix
2. Arrays. . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 13
JavaScript Arrays Defined 13
Using Arrays 13
Creating Arrays 14
Accessing and Writing Array Elements 15
Creating Arrays from Strings 15
Aggregate Array Operations 16
Accessor Functions 17
Searching for a Value 17
String Representations of Arrays 18
Creating New Arrays from Existing Arrays 18
Mutator Functions 19
Adding Elements to an Array 19
Removing Elements from an Array 20
iii
www.it-ebooks.info
Adding and Removing Elements from the Middle of an Array 21
Putting Array Elements in Order 22
Iterator Functions 23
Non–Array-Generating Iterator Functions 23
Iterator Functions That Return a New Array 25
Two-Dimensional and Multidimensional Arrays 27
Creating Two-Dimensional Arrays 27
Processing Two-Dimensional Array Elements 28
Jagged Arrays 30
Arrays of Objects 30
Arrays in Objects 31
Exercises 33
3. Lists. . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 35
A List ADT 35
A List Class Implementation 36
Append: Adding an Element to a List 37
Remove: Removing an Element from a List 37
Find: Finding an Element in a List 38
Length: Determining the Number of Elements in a List 38
toString: Retrieving a List’s Elements 38
Insert: Inserting an Element into a List 39
Clear: Removing All Elements from a List 39
Contains: Determining if a Given Value Is in a List 40
Traversing a List 40
Iterating Through a List 41
A List-Based Application 42
Reading Text Files 42
Using Lists to Manage a Kiosk 43
Exercises 47
4. Stacks. . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 49
Stack Operations 49
A Stack Implementation 50
Using the Stack Class 53
Multiple Base Conversions 53
Palindromes 54
Demonstrating Recursion 56
Exercises 57
5. Queues. . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 59
Queue Operations 59
iv | Table of Contents
www.it-ebooks.info
An Array-Based Queue Class Implementation 60
Using the Queue Class: Assigning Partners at a Square Dance 63
Sorting Data with Queues 67
Priority Queues 70
Exercises 72
6. Linked Lists. . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 73
Shortcomings of Arrays 73
Linked Lists Defined 74
An Object-Based Linked List Design 75
The Node Class 75
The Linked List Class 76
Inserting New Nodes 76
Removing Nodes from a Linked List 78
Doubly Linked Lists 81
Circularly Linked Lists 85
Other Linked List Functions 86
Exercises 86
7. Dictionaries. . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 89
The Dictionary Class 89
Auxiliary Functions for the Dictionary Class 91
Adding Sorting to the Dictionary Class 93
Exercises 94
8. Hashing. . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 97
An Overview of Hashing 97
A Hash Table Class 98
Choosing a Hash Function 98
A Better Hash Function 101
Hashing Integer Keys 103
Storing and Retrieving Data in a Hash Table 106
Handling Collisions 107
Separate Chaining 107
Linear Probing 109
Exercises 111
9. Sets. . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 113
Fundamental Set Definitions, Operations, and Properties 113
Set Definitions 113
Set Operations 114
The Set Class Implementation 114
Table of Contents | v
www.it-ebooks.info
More Set Operations 116
Exercises 120
vi | Table of Contents
www.it-ebooks.info
The Shellsort Algorithm 171
The Mergesort Algorithm 176
The Quicksort Algorithm 181
Exercises 186
Index. . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 221
www.it-ebooks.info
www.it-ebooks.info
Preface
Over the past few years, JavaScript has been used more and more as a server-side com‐
puter programming language owing to platforms such as Node.js and SpiderMonkey.
Now that JavaScript programming is moving out of the browser, programmers will find
they need to use many of the tools provided by more conventional languages, such as
C++ and Java. Among these tools are classic data structures such as linked lists, stacks,
queues, and graphs, as well as classic algorithms for sorting and searching data. This
book discusses how to implement these data structures and algorithms for server-side
JavaScript programming.
JavaScript programmers will find this book useful because it discusses how to implement
data structures and algorithms within the constraints that JavaScript places them, such
as arrays that are really objects, overly global variables, and a prototype-based object
system. JavaScript has an unfair reputation as a “bad” programming language, but this
book demonstrates how you can use JavaScript to develop efficient and effective data
structures and algorithms using the language’s “good parts.”
ix
www.it-ebooks.info
For many programmers who didn’t study computer science in school, the only data
structure they are familiar with is the array. Arrays are great for some problems, but for
many complex problems, they are simply not sophisticated enough. Most experienced
programmers will admit that for many programming problems, once they come up with
the proper data structure, the algorithms needed to solve the problem are easier to design
and implement.
An example of a data structure that leads to efficient algorithms is the binary search tree
(BST). A binary search tree is designed so that it is easy to find the minimum and
maximum values of a set of data, yielding an algorithm that is more efficient than the
best search algorithms available. Programmers unfamiliar with BSTs will instead prob‐
ably use a simpler data structure that ends up being less efficient.
Studying algorithms is important because there is always more than one algorithm that
can be used to solve a problem, and knowing which ones are the most efficient is im‐
portant for the productive programmer. For example, there are at least six or seven ways
to sort a list of data, but knowing that the Quicksort algorithm is more efficient than
the selection sort algorithm will lead to a much more efficient sorting process. Or that
it’s fairly easy to implement a sequential or linear search algorithm for a list of data, but
knowing that the binary sort algorithm can sometimes be twice as efficient as the se‐
quential search will lead to a better program.
The comprehensive study of data structures and algorithms teaches you not only which
data structures and which algorithms are the most efficient, but you also learn how to
decide which data structures and which algorithms are the most appropriate for the
problem at hand. There will often be trade-offs involved when writing a program, es‐
pecially in the JavaScript environment, and knowing the ins and outs of the various data
structures and algorithms covered in this book will help you make the proper decision
for any particular programming problem you are trying to solve.
x | Preface
www.it-ebooks.info
Organization of the Book
• Chapter 1 presents an overview of the JavaScript language, or at least the features
of the JavaScript language used in this book. This chapter also demonstrates through
use the programming style used throughout the other chapters.
• Chapter 2 discusses the most common data structure in computer programming:
the array, which is native to JavaScript.
• Chapter 3 introduces the first implemented data structure: the list.
• Chapter 4 covers the stack data structure. Stacks are used throughout computer
science in both compiler and operating system implementations.
• Chapter 5 discusses queue data structures. Queues are an abstraction of the lines
you stand in at a bank or the grocery store. Queues are used extensively in simulation
software where data has to be lined up before it is processed.
• Chapter 6 covers Linked lists. A linked list is a modification of the list data structure,
where each element is a separate object linked to the objects on either side of it.
Linked lists are efficient when you need to perform multiple insertions and dele‐
tions in your program.
• Chapter 7 demonstrates how to build and use dictionaries, which are data structures
that store data as key-value pairs.
• One way to implement a dictionary is to use a hash table, and Chapter 8 discusses
how to build hash tables and the hash algorithms that are used to store data in the
table.
• Chapter 9 covers the set data structure. Sets are often not covered in data structure
books, but they can be useful for storing data that is not supposed to have duplicates
in the data set.
• Binary trees and binary search trees are the subject of Chapter 10. As mentioned
earlier, binary search trees are useful for storing data that needs to be stored orig‐
inally in sorted form.
• Chapter 11 covers graphs and graph algorithms. Graphs are used to represent data
such as the nodes of a computer network or the cities on a map.
• Chapter 12 moves from data structures to algorithms and discusses various algo‐
rithms for sorting data, including both simple sorting algorithms that are easy to
implement but are not efficient for large data sets, and more complex algorithms
that are appropriate for larger data sets.
• Chapter 13 also covers algorithms, this time searching algorithms such as sequential
search and binary search.
• The last chapter of the book, Chapter 14, discusses a couple more advanced algo‐
rithms for working with data—dynamic programming and greedy algorithms.
Preface | xi
www.it-ebooks.info
These algorithms are useful for solving hard problems where a more traditional
algorithm is either too slow or too hard to implement. We examine some classic
problems for both dynamic programming and greedy algorithms in the chapter.
xii | Preface
www.it-ebooks.info
Safari® Books Online
Safari Books Online is an on-demand digital library that
delivers expert content in both book and video form from
the world’s leading authors in technology and business.
Technology professionals, software developers, web designers, and business and crea‐
tive professionals use Safari Books Online as their primary resource for research, prob‐
lem solving, learning, and certification training.
Safari Books Online offers a range of product mixes and pricing programs for organi‐
zations, government agencies, and individuals. Subscribers have access to thousands of
books, training videos, and prepublication manuscripts in one fully searchable database
from publishers like O’Reilly Media, Prentice Hall Professional, Addison-Wesley Pro‐
fessional, Microsoft Press, Sams, Que, Peachpit Press, Focal Press, Cisco Press, John
Wiley & Sons, Syngress, Morgan Kaufmann, IBM Redbooks, Packt, Adobe Press, FT
Press, Apress, Manning, New Riders, McGraw-Hill, Jones & Bartlett, Course Technol‐
ogy, and dozens more. For more information about Safari Books Online, please visit us
online.
How to Contact Us
Please address comments and questions concerning this book to the publisher:
We have a web page for this book, where we list errata, examples, and any additional
information. You can access this page at http://oreil.ly/data_structures_algorithms_JS.
To comment or ask technical questions about this book, send email to bookques
tions@oreilly.com.
For more information about our books, courses, conferences, and news, see our website
at http://www.oreilly.com.
Find us on Facebook: http://facebook.com/oreilly
Follow us on Twitter: http://twitter.com/oreillymedia
Watch us on YouTube: http://www.youtube.com/oreillymedia
Preface | xiii
www.it-ebooks.info
Random documents with unrelated
content Scribd suggests to you:
while the squaws and papooses were crossing the river, riding, or
swimming beside their swimming ponies.
The rear guard had at first run toward the front, but the front guard met
them halfway, and together they charged after the Indians. When near at
hand, Charles Elston was sent forward to offer those who would accept it
and come forward peacefully, immunity from punishment. They met his
offer with a shriek of defiance and charged furiously.
The Indians numbered more than five hundred warriors, and, when at a
distance of about three hundred yards, they commenced firing, and it was
answered in telling effect by the military. While those in front were checked
by the fire of the Gallagher rifles, both flanks of the Indians advanced as if
to hem them in and cut them off.
Over the hills from the west side of Horse Creek poured dozens and
hundreds of the shrieking demons, and an orderly retreat was taken to the
wagons, which, in the meantime, had been drawn up in a defensive circle,
and hastily constructed rifle pits made.
The Indians then ceased their firing and withdrew. Seeing that they were
indisposed to press their attack while the soldiers were behind defenses, and
wishing to keep them engaged and at hand until reënforcements came, the
officers in charge took fifty of the best mounted men and sallied out.
When out about three miles they saw a large force of Indians coming
around the hills on the west side of Horse Creek with the evident intention
of cutting them off. Again the military retired to their intrenchments.
About nine o’clock Captain Shuman arrived with a force from Camp
Shuman or Fort Mitchell, and, thus reënforced, another attack was made
upon the Indians, but it was a little late. The squaws and papooses had all
succeeded in crossing the river, and the warriors had followed.
The military could not follow, for it would be impractical, and perhaps
impossible to cross the river at its high stage, in the face of a superior
number of Indians.
A message had been sent to Fort Laramie, and Colonel Moonlight, well
known for his recent summary execution of three renegade Indians, had
started from the fort with two hundred and forty well-mounted men, when
he met another courier with the information that the Indians had crossed the
river, whereupon he crossed at the fort and took up the pursuit.
This constitutes another story, and the finish of the battle of Horse
Creek, the dead being the four named in the beginning of this article, and
four others were wounded. The dead were taken to Camp Shuman, the ruins
of which are still distinguishable, about three hundred feet south of the west
end of the Platte River Bridge, west of this city. And out southwest thereof
about a quarter of a mile they were laid to rest, and there have rested for this
half a century ending the middle of June. And now, from their obliterated
graves, they will be removed to join their fellows, the other early guardians
of the great Overland Trail, in the cemetery set aside for their honor by the
national government.
PRICE, FIVE CENTS PER COPY. If you want any back numbers of our
weeklies and cannot procure them from your news dealer, they can be
obtained direct from this office. Postage stamps taken the same as money.
STREET & SMITH, Publishers, 79-89 Seventh Ave., NEW YORK CITY
*** END OF THE PROJECT GUTENBERG EBOOK NICK CARTER
STORIES NO. 159, SEPTEMBER 25, 1915: DRIVEN FROM
COVER; OR, NICK CARTER'S DOUBLE RUSE ***
Updated editions will replace the previous one—the old editions will
be renamed.
1.D. The copyright laws of the place where you are located also
govern what you can do with this work. Copyright laws in most
countries are in a constant state of change. If you are outside the
United States, check the laws of your country in addition to the terms
of this agreement before downloading, copying, displaying,
performing, distributing or creating derivative works based on this
work or any other Project Gutenberg™ work. The Foundation makes
no representations concerning the copyright status of any work in
any country other than the United States.
• You pay a royalty fee of 20% of the gross profits you derive from
the use of Project Gutenberg™ works calculated using the
method you already use to calculate your applicable taxes. The
fee is owed to the owner of the Project Gutenberg™ trademark,
but he has agreed to donate royalties under this paragraph to
the Project Gutenberg Literary Archive Foundation. Royalty
payments must be paid within 60 days following each date on
which you prepare (or are legally required to prepare) your
periodic tax returns. Royalty payments should be clearly marked
as such and sent to the Project Gutenberg Literary Archive
Foundation at the address specified in Section 4, “Information
about donations to the Project Gutenberg Literary Archive
Foundation.”
• You comply with all other terms of this agreement for free
distribution of Project Gutenberg™ works.
1.F.
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.
ebookname.com