Linear (Sequential) Search

Linear Search is a simple algorithm used to find a specific value in an array or list. It works by checking each element one at a time until the desired value is found or the end of the collection is reached.

This algorithm does not require the data to be sorted, which makes it useful in many practical situations. However, because it may need to examine every element, it is not the most efficient choice for large datasets.

How It Works

Linear Search follows a straightforward process:

If the algorithm reaches the end without finding the target, it returns -1.

Because elements are checked one by one, the time required grows linearly with the size of the array.

JavaScript Example


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

// Example usage
const values = [4, 12, 7, 19, 3];

console.log(linearSearch(values, 7));  // 2
console.log(linearSearch(values, 10)); // -1