Linear Search

Time: O(n)Space: O(1)

💡How It Works

This search algorithm iterates through the array, comparing each element in the array with the target value. If equals, it stops and returns the corresponding index.

It's called "linear" search because it moves through the array in a straight line — one element at a time — until it finds the target, much like flipping through pages of a book one by one.

💻Implementation

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

🔍Deeper Look

Linear Search checks every element in the array one by one from the beginning, and stops when it finds a match. The array is not required to be sorted, making it useful to find a value in raw data. But the speed of this search is very slow, especially for large arrays, but it shines in situations where minimal overhead and universal applicability are key.

🔍 Always Works

Linear Search is one of the few algorithms which works on any dataset, whether the data is sorted or unsorted, or numerical or textual. So it is much more of a reliable option when quick setup matters more than speed.

🧙‍♂️ Variants in Practice

Variants like Sentinel Linear Search reduce the number of comparisons slightly, while Recursive Linear Search offers a functional approach in languages that support recursion.