Data Structures and Algorithms with JavaScript 1st Edition Michael Mcmillan download pdf
Data Structures and Algorithms with JavaScript 1st Edition Michael Mcmillan download pdf
com
https://ebookname.com/product/data-structures-and-
algorithms-with-javascript-1st-edition-michael-mcmillan/
OR CLICK BUTTON
DOWNLOAD EBOOK
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 [email protected].
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
[email protected].
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
Acknowledgments
There are always lots of people to thank when you’ve finished writing a book. I’d like to
thank my acquisition editor, Simon St. Laurent, for believing in this book and getting
me started writing it. Meghan Blanchette worked hard to keep me on schedule, and if
I went off schedule, it definitely wasn’t her fault. Brian MacDonald worked extremely
hard to make this book as understandable as possible, and he helped make several parts
of the text much clearer than I had written them originally. I also want to thank my
technical reviewers for reading all the text as well as the code, and for pointing out places
where both my prose and my code needed to be clearer. My colleague and illustrator,
Cynthia Fehrenbach, did an outstanding job translating my chicken scratchings into
crisp, clear illustrations, and she deserves extra praise for her willingness to redraw
several illustrations at the very last minute. Finally, I’d like to thank all the people at
Mozilla for designing an excellent JavaScript engine and shell and writing some excellent
documentation for using both the language and the shell.
xiv | Preface
www.it-ebooks.info
CHAPTER 1
The JavaScript Programming Environment
and Model
This chapter describes the JavaScript programming environment and the programming
constructs we’ll use in this book to define the various data structures and algorithms
examined.
www.it-ebooks.info
js> for (var i = 1; i < 6; ++i) {
print(i);
}
1
2
3
4
5
js>
You can enter arithmetic expressions and the shell will immediately evaluate them. You
can write any legal JavaScript statement and the shell will immediately evaluate it as
well. The interactive shell is great for exploring JavaScript statements to discover how
they work. To leave the shell when you are finished, type the command quit().
The other way to use the shell is to have it interpret complete JavaScript programs. This
is how we will use the shell throughout the rest of the book.
To use the shell to intepret programs, you first have to create a file that contains a
JavaScript program. You can use any text editor, making sure you save the file as plain
text. The only requirement is that the file must have a .js extension. The shell has to see
this extension to know the file is a JavaScript program.
Once you have your file saved, you interpret it by typing the js command followed by
the full filename of your program. For example, if you saved the for loop code fragment
that’s shown earlier in a file named loop.js, you would enter the following:
c:\js>js loop.js
which would produce the following output:
1
2
3
4
5
After the program is executed, control is returned to the command prompt.
www.it-ebooks.info
Declaring and Intializing Variables
JavaScript variables are global by default and, strictly speaking, don’t have to be declared
before using. When a JavaScript variable is initialized without first being declared, it
becomes a global variable. In this book, however, we follow the convention used with
compiled languages such as C++ and Java by declaring all variables before their first
use. The added benefit to doing this is that declared variables are created as local vari‐
ables. We will talk more about variable scope later in this chapter.
To declare a variable in JavaScript, use the keyword var followed by a variable name,
and optionally, an assignment expression. Here are some examples:
var number;
var name;
var rate = 1.2;
var greeting = "Hello, world!";
var flag = false;
• + (addition)
• - (subtraction)
• * (multiplication)
• / (division)
• % (modulo)
JavaScript also has a math library you can use for advanced functions such as square
root, absolute value, and the trigonometric functions. The arithmetic operators follow
the standard order of operations, and parentheses can be used to modify that order.
Example 1-1 shows some examples of performing arithmetic in JavaScript, as well as
examples of using several of the mathematical functions.
Example 1-1. Arithmetic and math functions in JavaScript
var x = 3;
var y = 1.1;
print(x + y);
print(x * y);
print((x+y)*(x-y));
var z = 9;
print(Math.sqrt(z));
print(Math.abs(y/x));
www.it-ebooks.info
4.1
3.3000000000000003
7.789999999999999
3
0.3666666666666667
If you don’t want or need the precision shown above, you can format a number to a
fixed precision:
var x = 3;
var y = 1.1;
var z = x * y;
print(z.toFixed(2)); // displays 3.30
Decision Constructs
Decision constructs allow our programs to make decisions on what programming
statements to execute based on a Boolean expression. The two decision constructs we
use in this book are the if statement and the switch statement.
The if statement comes in three forms:
www.it-ebooks.info
else {
mid = (current+high) / 2;
}
The other decision structure we use in this book is the switch statement. This statement
provides a cleaner, more structured construction when you have several simple deci‐
sions to make. Example 1-5 demonstrates how the switch statement works.
www.it-ebooks.info
monthName = "July";
break;
case "8":
monthName = "August";
break;
case "9":
monthName = "September";
break;
case "10":
monthName = "October";
break;
case "11":
monthName = "November";
break;
case "12":
monthName = "December";
break;
default:
print("Bad input");
}
Is this the most efficient way to solve this problem? No, but it does a great job of dem‐
onstrating how the switch statement works.
One major difference between the JavaScript switch statement and switch statements
in other programming languages is that the expression that is being tested in the state‐
ment can be of any data type, as opposed to an integral data type, as required by languages
such as C++ and Java. In fact, you’ll notice in the previous example that we use the
month numbers as strings, rather than converting them to numbers, since we can com‐
pare strings using the switch statement in JavaScript.
Repetition Constructs
Many of the algorithms we study in this book are repetitive in nature. We use two
repetition constructs in this book—the while loop and the for loop.
When we want to execute a set of statements while a condition is true, we use a while
loop. Example 1-6 demonstrates how the while loop works.
www.it-ebooks.info
When we want to execute a set of statements a specified number of times, we use a for
loop. Example 1-7 uses a for loop to sum the integers 1 through 10.
for loops are also used frequently to access the elements of an array, as shown in
Example 1-8.
Functions
JavaScript provides the means to define both value-returning functions and functions
that don’t return values (sometimes called subprocedures or void functions).
Example 1-9 demonstrates how value-returning functions are defined and called in
JavaScript.
Example 1-9. A value-returning function
function factorial(number) {
var product = 1;
for (var i = number; i >= 1; --i) {
product *= i;
}
return product;
}
print(factorial(4)); // displays 24
print(factorial(5)); // displays 120
print(factorial(10)); // displays 3628800
Example 1-10 illustrates how to write a function that is used not for its return value, but
for the operations it performs.
www.it-ebooks.info
Example 1-10. A subprocedure or void function in JavaScript
function curve(arr, amount) {
for (var i = 0; i < arr.length; ++i) {
arr[i] += amount;
}
}
All function parameters in JavaScript are passed by value, and there are no reference
parameters. However, there are reference objects, such as arrays, which are passed to
functions by reference, as was demonstrated in Example 1-10.
Variable Scope
The scope of a variable refers to where in a program a variable’s value can be accessed.
The scope of a variable in JavaScript is defined as function scope. This means that a
variable’s value is visible within the function definition where the variable is declared
and defined and within any functions that are nested within that function.
When a variable is defined outside of a function, in the main program, the variable is
said to have global scope, which means its value can be accessed by any part of a program,
including functions. The following short program demonstrates how global scope
works:
function showScope() {
return scope;
}
The function showScope() can access the variable scope because scope is a global vari‐
able. Global variables can be declared at any place in a program, either before or after
function definitions.
Now watch what happens when we define a second scope variable within the show
Scope() function:
function showScope() {
var scope = "local";
return scope;
}
www.it-ebooks.info
The scope variable defined in the showScope() function has local scope, while the scope
variable defined in the main program is a global variable. Even though the two variables
have the same name, their scopes are different, and their values are different when
accessed within the area of the program where they are defined.
All of this behavior is normal and expected. However, it can all change if you leave off
the keyword var in the variable definitions. JavaScript allows you to define variables
without using the var keyword, but when you do, that variable automatically has global
scope, even if defined within a function.
Example 1-11 demonstrates the ramifications of leaving off the var keyword when
defining variables.
Example 1-11. The ramification of overusing global variables
function showScope() {
scope = "local";
return scope;
}
scope = "global";
print(scope); // displays "global"
print(showScope()); // displays "local"
print(scope); // displays "local"
In Example 1-11, because the scope variable inside the function is not declared with the
var keyword, when the string "local" is assigned to the variable, we are actually chang‐
ing the value of the scope variable in the main program. You should always begin every
definition of a variable with the var keyword to keep things like this from happening.
Earlier, we mentioned that JavaScript has function scope. This means that JavaScript
does not have block scope, unlike many other modern programming languages. With
block scope, you can declare a variable within a block of code and the variable is not
accessible outside of that block, as you typically see with a C++ or Java for loop:
for (int i = 1; i <=10; ++i) {
cout << "Hello, world!" << endl;
}
Even though JavaScript does not have block scope, we pretend like it does when we write
for loops in this book:
for (var i = 1; i <= 10; ++i ) {
print("Hello, world!");
}
We don’t want to be the cause of you picking up bad programming habits.
www.it-ebooks.info
Random documents with unrelated
content Scribd suggests to you:
cause était gagnée d'avance; en huit heures nous avions à peine
parcouru vingt-cinq kilomètres!
A Ferachbad les stipes des palmiers servaient à couvrir les
maisons: ici le feuillage constitue les murs et les toitures. Le premier
gîte mis à ma disposition était une hutte de forme conique
composée de branches fichées en terre et liées en faisceau à leur
extrémité supérieure. Une habitation d'un autre modèle m'a paru
présenter d'incontestables avantages. Aux quatre angles s'élèvent
des fûts de palmiers réunis par des sablières; des colonnes
soutiennent à l'intérieur une charpente horizontale qui vient
s'appuyer sur l'enceinte; les murs sont faits en fagots attachés les
uns aux autres par des cordes de sparterie. Une natte couvre le sol
de ce palais hypostyle, dont les indigènes arrosent les toitures à
grande eau pendant les plus chaudes heures du jour.
VILLAGE D'AHARAM.