The sequential search

The sequential search 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:

const DOES_NOT_EXIST = -1;function sequentialSearch(array, value, equalsFn = defaultEquals) {  for (let i = 0; i < array.length; i++) { // {1}    if (equalsFn(value, array[i])) { // {2}      return i; // {3}    }  }  return DOES_NOT_EXIST; // {4}} 

The sequential search iterates through the array ({1}) and compares each value with the value we are searching for ({2}). If we find it, we can return something to indicate that we found it. We can return the value itself, the value true, or its ...

Get Learning JavaScript Data Structures and Algorithms - Third Edition now with the O’Reilly learning platform.

O’Reilly members experience books, live events, courses curated by job role, and more from O’Reilly and nearly 200 top publishers.