Book Image

Learning JavaScript Data Structures and Algorithms - Second Edition

By : Loiane Groner
Book Image

Learning JavaScript Data Structures and Algorithms - Second Edition

By: Loiane Groner

Overview of this book

This book begins by covering basics of the JavaScript language and introducing ECMAScript 7, before gradually moving on to the current implementations of ECMAScript 6. You will gain an in-depth knowledge of how hash tables and set data structure functions, as well as how trees and hash maps can be used to search files in a HD or represent a database. This book is an accessible route deeper into JavaScript. Graphs being one of the most complex data structures you’ll encounter, we’ll also give you a better understanding of why and how graphs are largely used in GPS navigation systems in social networks. Toward the end of the book, you’ll discover how all the theories presented by this book can be applied in real-world solutions while working on your own computer networks and Facebook searches.
Table of Contents (18 chapters)
Learning JavaScript Data Structures and Algorithms - Second Edition
Credits
About the Author
About the Reviewer
www.PacktPub.com
Preface

Searching algorithms


Now, let's talk about searching algorithms. If we take a look at the algorithms we implemented in previous chapters, such as the search method of the BinarySearchTree class ( Chapter 8 , Trees) or the indexOf method of the LinkedList class ( Chapter 5 , Linked Lists), these are all search algorithms, and of course, each one was implemented according to the behavior of its data structure. So we are already familiar with two-search algorithm; we just do not know their "official" names yet!

The sequential search

The sequential or linear search is the most basic search algorithm. It consists of comparing each element of the data structure with the one we are looking for. It is also the most inefficient one.

Let's take a look at its implementation:

this.sequentialSearch = function(item){ 
  for (var i=0; i<array.length; i++){ //{1} 
    if (item === array[i]){         //{2} 
      return i;                   //{3} 
    } 
  } 
  return -1;  /...