Learning JavaScript Data Structures and Algorithms
5/5
()
About this ebook
A data structure is a particular way of organizing data in a computer to utilize resources efficiently. Data structures and algorithms are the base of every solution to any programming problem.
This book begins by covering the basics of the JavaScript language and then moves on to discuss the most important data structures such as array, queue, stack, and linked list. You will also gain an in-depth knowledge of how hash tables and set data structure function. After this, you will be taught what trees are, and how to use the binary tree and the binary search tree.
In subsequent chapters, you will learn about graphs, DFS, and BFS. Finally, we will round off by learning how to differentiate between various searching and sorting algorithms such as sequential search, binary search, quick sort, bubble sort, and so on, and how to implement them. Towards the end of the book, you will also be introduced to dynamic programming.
Loiane Groner
Loiane Groner lives in São Paulo, Brazil, and has over 8 years of software development experience. While at university, Loiane demonstrated great interest in IT. She worked as a Teaching Assistant for 2 years and 6 months in the Algorithms, Data Structures, and Computing Theory Department. She represented her university at the ACM International Collegiate Programming Contest - Brazilian Finals (South America Regionals) and also worked as Student Delegate of SBC (Brazilian Computing Society) for 2 years. She won a merit award in her senior year for being one of the top 3 students with the best GPAs in the Computer Science department, and she also graduated with honors.She has already in her career worked at multinational companies such as IBM. Her areas of expertise include Java SE and Java EE and also Sencha technologies (Ext JS and Sencha Touch). Nowadays, she is working as a Software Development Manager at a financial institution, where she manages overseas solutions. She also works as an independent Sencha consultant and coach.Loiane is also the author of Ext JS 4 First Look and Mastering Ext JS, both published by Packt.She is passionate about Sencha and Java, and she is the CampinasJUG (Campinas Java Users Group) leader and ESJUG (Espirito Santo Java Users Group) coordinator, both of which are Brazilian JUGs.Loiane also contributes to the software development community through her blogs: http://loianegroner.com (English) and http://loiane.com (Portuguese-BR), where she writes about her IT career, Ext JS, Sencha Touch, Spring Framework, and she also discusses general development notes and publishes screencasts.
Read more from Loiane Groner
Learning JavaScript Data Structures and Algorithms - Second Edition Rating: 0 out of 5 stars0 ratingsMastering Ext JS - Second Edition Rating: 0 out of 5 stars0 ratingsJavaScript Regular Expressions Rating: 3 out of 5 stars3/5Angular Design Patterns and Best Practices: Create scalable and adaptable applications that grow to meet evolving user needs Rating: 0 out of 5 stars0 ratings
Related to Learning JavaScript Data Structures and Algorithms
Related ebooks
Clean Code in JavaScript: Develop reliable, maintainable, and robust JavaScript Rating: 5 out of 5 stars5/5TypeScript Essentials Rating: 4 out of 5 stars4/5Responsive Web Design with HTML5 and CSS3 Essentials Rating: 5 out of 5 stars5/5Node.js High Performance Rating: 0 out of 5 stars0 ratingsLearning Functional Data Structures and Algorithms Rating: 0 out of 5 stars0 ratingsPython Data Structures and Algorithms Rating: 5 out of 5 stars5/5Express Web Application Development Rating: 3 out of 5 stars3/5Mastering JavaScript Design Patterns Rating: 4 out of 5 stars4/5JavaScript and JSON Essentials Rating: 5 out of 5 stars5/5Object-Oriented JavaScript: Create scalable, reusable high-quality JavaScript applications, and libraries Rating: 3 out of 5 stars3/5JavaScript Enlightenment Rating: 4 out of 5 stars4/5Mastering JavaScript Rating: 4 out of 5 stars4/5Mastering JavaScript Design Patterns - Second Edition Rating: 5 out of 5 stars5/5JavaScript Unlocked Rating: 5 out of 5 stars5/5The Joy of JavaScript Rating: 0 out of 5 stars0 ratingsObject-Oriented JavaScript Rating: 4 out of 5 stars4/5Object-Oriented JavaScript - Third Edition Rating: 4 out of 5 stars4/5Professional JavaScript for Web Developers Rating: 0 out of 5 stars0 ratingsLearn NodeJS in 1 Day: Complete Node JS Guide with Examples Rating: 3 out of 5 stars3/550 Recipes for Programming Node.js Rating: 3 out of 5 stars3/5JavaScript: Advanced Guide to Programming Code with JavaScript Rating: 0 out of 5 stars0 ratingsMastering JavaScript: The Complete Guide to JavaScript Mastery Rating: 5 out of 5 stars5/5Learn JavaScript in 24 Hours Rating: 3 out of 5 stars3/5Learning jQuery Rating: 4 out of 5 stars4/5JavaScript: Beginner's Guide to Programming Code with JavaScript: JavaScript Computer Programming Rating: 0 out of 5 stars0 ratingsJavaScript: Tips and Tricks to Programming Code with Javascript: JavaScript Computer Programming, #2 Rating: 0 out of 5 stars0 ratings
Computers For You
Elon Musk Rating: 4 out of 5 stars4/5Procreate for Beginners: Introduction to Procreate for Drawing and Illustrating on the iPad Rating: 5 out of 5 stars5/5Deep Search: How to Explore the Internet More Effectively Rating: 5 out of 5 stars5/5Learning the Chess Openings Rating: 5 out of 5 stars5/5Slenderman: Online Obsession, Mental Illness, and the Violent Crime of Two Midwestern Girls Rating: 4 out of 5 stars4/5Mastering ChatGPT: 21 Prompts Templates for Effortless Writing Rating: 4 out of 5 stars4/5The Innovators: How a Group of Hackers, Geniuses, and Geeks Created the Digital Revolution Rating: 4 out of 5 stars4/5CompTIA Security+ Get Certified Get Ahead: SY0-701 Study Guide Rating: 5 out of 5 stars5/5The Professional Voiceover Handbook: Voiceover training, #1 Rating: 5 out of 5 stars5/5SQL QuickStart Guide: The Simplified Beginner's Guide to Managing, Analyzing, and Manipulating Data With SQL Rating: 4 out of 5 stars4/5Some Future Day: How AI Is Going to Change Everything Rating: 0 out of 5 stars0 ratingsExcel 101: A Beginner's & Intermediate's Guide for Mastering the Quintessence of Microsoft Excel (2010-2019 & 365) in no time! Rating: 0 out of 5 stars0 ratingsAn Ultimate Guide to Kali Linux for Beginners Rating: 3 out of 5 stars3/5The ChatGPT Millionaire Handbook: Make Money Online With the Power of AI Technology Rating: 4 out of 5 stars4/5The Self-Taught Computer Scientist: The Beginner's Guide to Data Structures & Algorithms Rating: 0 out of 5 stars0 ratingsStandard Deviations: Flawed Assumptions, Tortured Data, and Other Ways to Lie with Statistics Rating: 4 out of 5 stars4/5How to Create Cpn Numbers the Right way: A Step by Step Guide to Creating cpn Numbers Legally Rating: 4 out of 5 stars4/5101 Awesome Builds: Minecraft® Secrets from the World's Greatest Crafters Rating: 4 out of 5 stars4/5Alan Turing: The Enigma: The Book That Inspired the Film The Imitation Game - Updated Edition Rating: 4 out of 5 stars4/5A Brief History of Artificial Intelligence: What It Is, Where We Are, and Where We Are Going Rating: 4 out of 5 stars4/5Going Text: Mastering the Command Line Rating: 4 out of 5 stars4/5Tor and the Dark Art of Anonymity Rating: 5 out of 5 stars5/5Python Machine Learning By Example Rating: 4 out of 5 stars4/5The Hacker Crackdown: Law and Disorder on the Electronic Frontier Rating: 4 out of 5 stars4/5CompTia Security 701: Fundamentals of Security Rating: 0 out of 5 stars0 ratingsUncanny Valley: A Memoir Rating: 4 out of 5 stars4/5
Reviews for Learning JavaScript Data Structures and Algorithms
1 rating0 reviews
Book preview
Learning JavaScript Data Structures and Algorithms - Loiane Groner
Table of Contents
Learning JavaScript Data Structures and Algorithms
Credits
About the Author
Acknowledgments
About the Reviewers
www.PacktPub.com
Support files, eBooks, discount offers, and more
Why subscribe?
Free access for Packt account holders
Preface
What this book covers
What you need for this book
Who this book is for
Conventions
Reader feedback
Customer support
Downloading the example code
Downloading the color images of this book
Errata
Piracy
Questions
1. JavaScript – A Quick Overview
Setting up the environment
The browser is enough
Using web servers (XAMPP)
It's all about JavaScript (Node.js)
JavaScript basics
Variables
Variable scope
Operators
Truthy and falsy
The equals operators (== and ===)
Control structures
Conditional statements
Loops
Functions
Object-oriented programming
Debugging and tools
Summary
2. Arrays
Why should we use arrays?
Creating and initializing arrays
Adding and removing elements
Two-dimensional and multi-dimensional arrays
References for JavaScript array methods
Joining multiple arrays
Iterator functions
Searching and sorting
Custom sorting
Sorting strings
Searching
Outputting the array into a string
Summary
3. Stacks
Creating a stack
The complete Stack class
Using the Stack class
Decimal to binary
Summary
4. Queues
Creating a queue
The complete Queue class
Using the Queue class
The priority queue
The circular queue – Hot Potato
Summary
5. Linked Lists
Creating a linked list
Appending elements to the end of the linked list
Removing elements from the linked list
Inserting an element at any position
Implementing other methods
The toString method
The indexOf method
The isEmpty, size, and getHead methods
Doubly linked lists
Inserting a new element at any position
Removing elements from any position
Circular linked lists
Summary
6. Sets
Creating a set
The has (value) method
The add method
The remove and clear methods
The size method
The values method
Using the Set class
Set operations
Set union
Set intersection
Set difference
Subset
Summary
7. Dictionaries and Hashes
Dictionaries
Creating a dictionary
The has and set methods
The remove method
The get and values methods
The clear, size, keys, and getItems methods
Using the Dictionary class
The hash table
Creating a hash table
Using the HashTable class
Hash table versus hash set
Handling collisions between hash tables
Separate chaining
The put method
The get method
The remove method
Linear probing
The put method
The get method
The remove method
Creating better hash functions
Summary
8. Trees
Trees terminology
Binary tree and binary search tree
Creating the BinarySearchTree class
Inserting a key in a tree
Tree traversal
In-order traversal
Pre-order traversal
Post-order traversal
Searching for values in a tree
Searching for minimum and maximum values
Searching for a specific value
Removing a node
Removing a leaf node
Removing a node with a left or right child
Removing a node with two children
More about binary trees
Summary
9. Graphs
Graph terminology
Directed and undirected graphs
Representing a graph
The adjacency matrix
The adjacency list
The incidence matrix
Creating the Graph class
Graph traversals
Breadth-first search (BFS)
Finding the shortest paths using BFS
Further studies on the shortest paths algorithms
Depth-first search (DFS)
Exploring the DFS algorithm
Topological sorting using DFS
Summary
10. Sorting and Searching Algorithms
Sorting algorithms
Bubble sort
Improved bubble sort
Selection sort
Insertion sort
Merge sort
Quick sort
The partition process
Quick sort in action
Searching algorithms
Sequential search
Binary search
Summary
Index
Learning JavaScript Data Structures and Algorithms
Learning JavaScript Data Structures and Algorithms
Copyright © 2014 Packt Publishing
All rights reserved. No part of this book may be reproduced, stored in a retrieval system, or transmitted in any form or by any means, without the prior written permission of the publisher, except in the case of brief quotations embedded in critical articles or reviews.
Every effort has been made in the preparation of this book to ensure the accuracy of the information presented. However, the information contained in this book is sold without warranty, either express or implied. Neither the author, nor Packt Publishing, and its dealers and distributors will be held liable for any damages caused or alleged to be caused directly or indirectly by this book.
Packt Publishing has endeavored to provide trademark information about all of the companies and products mentioned in this book by the appropriate use of capitals. However, Packt Publishing cannot guarantee the accuracy of this information.
First published: October 2014
Production reference: 1201014
Published by Packt Publishing Ltd.
Livery Place
35 Livery Street
Birmingham B3 2PB, UK.
ISBN 978-1-78355-487-4
www.packtpub.com
Credits
Author
Loiane Groner
Reviewers
Yaroslav Bigus
Maxwell Dayvson Da Silva
Vincent Lark
Vishal Rajpal
Commissioning Editor
Kunal Parikh
Acquisition Editor
Subho Gupta
Content Development Editor
Akashdeep Kundu
Technical Editors
Madhuri Das
Nikhil Potdukhe
Copy Editors
Maria Gould
Ameesha Green
Paul Hindle
Project Coordinator
Neha Thakur
Proofreaders
Simran Bhogal
Ameesha Green
Indexers
Mariammal Chettiyar
Tejal Soni
Graphics
Ronak Dhruv
Valentina D'silva
Abhinash Sahu
Production Coordinator
Conidon Miranda
Cover Work
Conidon Miranda
About the Author
Loiane Groner lives in São Paulo, Brazil, and has over 8 years of software development experience. While at university, she demonstrated a great interest in IT. She worked as an assistant teacher for two and a half years teaching Algorithms, Data Structures, and Computing Theory. She represented her university at the ACM International Collegiate Programming Contest—Brazilian finals (South America regionals), and also worked as student delegate of the Brazilian Computing Society (SBC) for 2 years. She won a merit award in her senior year for being one of the top three students in the Computer Science department and graduated with honors.
She has previously worked at multinational companies such as IBM. Her areas of expertise include Java SE and Java EE as well as Sencha technologies (Ext JS and Sencha Touch). Nowadays, she works as a software development manager at a financial institution, where she manages overseas solutions. She also works as an independent Sencha consultant and coach.
Loiane is also the author of Ext JS 4 First Look, Mastering Ext JS, and Sencha Architect App Development, all published by Packt Publishing.
She is passionate about Sencha and Java, and is the Campinas Java Users Group (CampinasJUG) leader and Espirito Santo Java Users Group (ESJUG) coordinator, both Brazilian JUGs.
Loiane also contributes to the software development community through her blogs at http://loianegroner.com (English) and http://loiane.com (Brazilian Portuguese), where she writes about her IT career, Ext JS, Sencha Touch, PhoneGap, Spring Framework, and general development notes as well as publishing screencasts.
If you want to get in touch, you can find Loiane on Facebook (https://www.facebook.com/loianegroner) and Twitter (@loiane).
Acknowledgments
I would like to thank my parents for giving me education, guidance, and advice over all these years and for helping me to be a better human being and professional. A very special thanks to my husband, for being patient and supportive and giving me encouragement.
I would also like to thank my professors from FAESA, who taught me about the algorithms and data structures presented in this book.
Also, a big thanks to my friends and readers for all the support. It is really nice when people get in touch at conferences and by any social network mentioning that they have read one of my books and give me feedback. Thank you very much!
About the Reviewers
Yaroslav Bigus is an expert in building cross-platform web and mobile applications. He has over 5 years of experience in development and has worked for companies in Leeds and New York. He has been using the .NET Framework stack to develop backend systems; JavaScript, AngularJS, jQuery, and Underscore for the frontend; and Xamarin for mobile devices.
He is currently working for an Israeli start-up named yRuler (Tangiblee). Previously, he has reviewed Xamarin Mobile Application Development for iOS and iOS Development with Xamarin Cookbook, both by Packt Publishing.
I am thankful to my friends and family for their support and love.
Maxwell Dayvson Da Silva is a native Brazilian who works as a software architect for The New York Times. He has more than 11 years of experience working for two of Brazil's leading digital media companies. His work at Terra, a global digital media company, helped reach an audience of over 100 million people monthly with entertainment, sports, and news content. Later, he was part of Globo.com, the largest media conglomerate in Latin America. His contribution in the digital media field is only a portion of how he spends his time. Combining his passion for art and science, he creates games and interactive art installations. Inspired by his son, Arthur, he continually searches for new ways to spread science in a fun way to children both in NYC and Brazil. He can be reached at https://github.com/dayvson.
I would like to say thank you to Juliane Inês do Nascimento for taking care of Arthur in such an amazing way while I am away. You are an amazing mother!
Vincent Lark is an experienced programmer who has worked as a backend and frontend web developer for web start-ups in Luxembourg and France. He now focuses on creating modern web UIs and develops games as a hobby. He has also reviewed the book WebGL HOTSHOT, Packt Publishing.
Vishal Rajpal is an experienced software engineer who started developing professional software applications in 2011. He has worked primarily on Java, JavaScript, and multiplatform mobile application development platforms including PhoneGap and Titanium.
At present, he is pursuing his Master's degree in Computer Science from Northeastern University, Seattle, and has been working on Scheme (Lisp), Objective-C, computer systems, and algorithms.
He lives in Seattle and can be reached at <[email protected]>. You can also find out more about his work at https://github.com/vishalrajpal/ and https://www.vishal-rajpal.blogspot.com. He has also reviewed the book PhoneGap 3.x Mobile Application Development HOTSHOT, Packt Publishing.
www.PacktPub.com
Support files, eBooks, discount offers, and more
You might want to visit www.PacktPub.com for support files and downloads related to your book.
Did you know that Packt offers eBook versions of every book published, with PDF and ePub files available? You can upgrade to the eBook version at www.PacktPub.com and as a print book customer, you are entitled to a discount on the eBook copy. Get in touch with us at
At www.PacktPub.com, you can also read a collection of free technical articles, sign up for a range of free newsletters and receive exclusive discounts and offers on Packt books and eBooks.
http://PacktLib.PacktPub.com
Do you need instant solutions to your IT questions? PacktLib is Packt's online digital book library. Here, you can access, read and search across Packt's entire library of books.
Why subscribe?
Fully searchable across every book published by Packt
Copy and paste, print and bookmark content
On demand and accessible via web browser
Free access for Packt account holders
If you have an account with Packt at www.PacktPub.com, you can use this to access PacktLib today and view nine entirely free books. Simply use your login credentials for immediate access.
Preface
JavaScript is currently the most popular programming language. It is known as the Internet language
due to the fact that Internet browsers understand JavaScript natively, without installing any plugins. JavaScript has grown so much that it is no longer just a frontend language; it is now also present on the server (Node.js) and database as well (MongoDB).
Understanding data structures is very important for any technology professional. Working as a developer means you have the ability to solve problems with the help of programming languages and data structures. They are an indispensable piece of the solutions we need to create to solve these problems. Choosing the wrong data structure can also impact the performance of the program we are writing. This is why it is important to get to know different data structures and how to apply them properly.
Algorithms play a major role in the art of Computer Science. There are so many ways of solving the same problem, and some approaches are better than others. That is why it is also very important to know the most famous algorithms.
Happy coding!
What this book covers
Chapter 1, JavaScript – A Quick Overview, covers the basics of JavaScript you need to know prior to learning about data structures and algorithms. It also covers setting up the development environment needed for this book.
Chapter 2, Arrays, explains how to use the most basic and most used data structure arrays. This chapter demonstrates how to declare, initialize, add, and remove elements from an array. It also covers how to use the native JavaScript array methods.
Chapter 3, Stacks, introduces the stack data structure, demonstrating how to create a stack and how to add and remove elements. It also demonstrates how to use stacks to solve some Computer Science problems.
Chapter 4, Queues, covers the queue data structure, demonstrating how to create a queue and add and remove elements. It also demonstrates how to use queues to solve some Computer Science problems and the major differences between queues and stacks.
Chapter 5, Linked Lists, explains how to create the linked list data structure from scratch using objects and the pointer concept. Besides covering how to declare, create, add, and remove elements, it also covers the various types of linked lists such as doubly linked lists and circular linked lists.
Chapter 6, Sets, introduces the set data structure and how it can be used to store non-repeated elements. It also explains the different types of set operations and how to implement and use them.
Chapter 7, Dictionaries and Hashes, explains the dictionary and hash data structures and the differences between them. This chapter covers how to declare, create, and use both data structures. It also explains how to handle collisions in hashes and techniques to create better hash functions.
Chapter 8, Trees, covers the tree data structure and its terminologies, focusing on binary search tree data as well as the methods trees use to search, traverse, add, and remove nodes. It also introduces the next steps you can take to delve deeper into the world of trees, covering what tree algorithms should be learned next.
Chapter 9, Graphs, introduces the amazing world of the graphs data structure and its application in real-world problems. This chapter covers the most common graph terminologies, the different ways of representing a graph, how to traverse graphs using the breadth-first search and depth-first search algorithms, and its applications.
Chapter 10, Sorting and Searching Algorithms, explores the most used sorting algorithms such as bubble sort (and its improved version), selection sort, insertion sort, merge sort, and quick sort. It also covers searching algorithms such as sequential and binary search.
Chapter 11, More About Algorithms, introduces some algorithm techniques and the famous big-O notation. It covers the recursion concept and some advanced algorithm techniques such as dynamic programming and greedy algorithms. This chapter introduces big-O notation and its concepts. Finally, it explains how to take your algorithm knowledge to the next level. This is an online chapter available on the Packt Publishing website. You can download it from https://www.packtpub.com/sites/default/files/downloads/4874OS_Chapter11_More_About_Algorithms.pdf.
Appendix, Big-O Cheat Sheet, lists the complexities of the algorithms (using big-O notation) implemented in this book. This is also an online chapter, which can be downloaded from https://www.packtpub.com/sites/default/files/downloads/4874OS_Appendix_Big_O_Cheat_Sheet.pdf.
What you need for this book
You can set up three different development environments for this book. You do not need to have all three environments; you can select one or give all of them a try!
For the first option, you need a browser. It is recommended to use one of the following browsers:
Chrome (https://www.google.com/chrome/browser/)
Firefox (https://www.mozilla.org/en-US/firefox/new/)
For the second option, you will need:
One of the browsers listed in the first option
A web server; if you do not have any web server installed in your computer, you can install XAMPP (https://www.apachefriends.org)
The third option is an environment 100 percent JavaScript! For this, you will need the following elements:
One of the