JavaScript JunkiesJavaScript Junkies Unleash Your Coding Superpowers with JavaScript Junkies

Find It Fast with Linear Search: The Simplest Search Algorithm Explained!

What is Linear Search Algorithm?

Linear search, also known as sequential search, is a search algorithm that checks each element of an array one by one until it finds the target value or reaches the end of the array.

Here’s an example implementation of linear search in JavaScript:

function linearSearch(array, target) {
  for (let i = 0; i < array.length; i++) {
    if (array[i] === target) {
      return i;
    }
  }

  return -1;
}

Here, the function linearSearch takes two arguments: array, which is the array to search, and target, which is the value to search for. The function uses a for loop to iterate over each element of the array. On each iteration, the function checks if the current element is equal to the target value. If it is, the function returns the index of the current element.

If the target value is not found in the array, the function returns -1 to indicate that the target is not present.

Here’s an example of how to use the linearSearch function:

const myArray = [1, 3, 5, 7, 9];
const index = linearSearch(myArray, 5);
console.log(index); // Output: 2

In this example, the linearSearch function is used to find the index of the value 5 in the myArray array. The function returns 2, which is the index of the value 5 in the array.

However, it’s worth noting that linear search has a time complexity of O(n), which means that as the size of the array grows, the amount of time it takes to search the array grows linearly. For larger arrays, binary search is often a more efficient algorithm.

Press ESC to close