DEV Community

generally23
generally23

Posted on

Linear Searching Algorithm in Javascript

Naive Linear Searching Approach

First what is linear search?

Linear search is the process of looking for a certain value in a list or set of values (e.g) looking for a value in a javascript array in a linear fashion, which means looking by order since javascript arrays are indexed we can compare what we're looking for to the current value we're looking at in the array and return true if we find it, false if not. note that there are different ways of searching but in this particular post we're going to focus on linear search only

Implementation

// first, let's create the function used to do the search
// as you can see in this post I am using ES6(new version of Javascript)
const linearSearch = (arr, query) => {
    let i;
    for (i = 0; i < arr.length; i++) {
      let currentValue = arr[i];
      if (query === currentValue) {
         return i;
      } 
    }
    return -1; 
}
// Hell no!!! what is all of this? don't worry it's simple

javascript
/*
1. First we created a function called linearSearch.
2. We passed two arguments to our function.
3. The first argument is the list we are searching in.
4. The second argument is the value to look for inside the list.
5. We declared a variable called i.
6. Now we want to iterate or (loop) over the list.
7. We are comparing the currentValue on the list to the query argument
8. if they are equal we are returning the index we found the value we were looking for.
9. if not we are returning -1 which means we did not found it.
/*

That's it Enjoy!!!




Top comments (0)