Book Image

Learning JavaScript Data Structures and Algorithms

By : Loiane Avancini
Book Image

Learning JavaScript Data Structures and Algorithms

By: Loiane Avancini

Overview of this book

Table of Contents (18 chapters)

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-searches algorithm, we just do not know their "official" names yet!

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;  //{4}
};

The sequential...