DEV Community


Posted on

Linear Search Algorithm

Linear search is easy to implement. It is ideal to use when finding an element within a sorted or unsorted list with a few items. The best-case performance of this search algorithm is O(1), and the worst-case performance is O(n).

Let's say we have 5 shuffled flashcards with random names written on each.

Robert, Janeth, Samuel, Harold, and Mark

So if we want to find the name Samuel, we need to check each card from the first card until we find a match.

Flash cards

Let's see it in action:

const flashCards = ['Robert', 'Janeth', 'Samuel', 'Harold', 'Mark']

const linearSearch = (flashCards, nameToFind) => {
  for(let i = 0; i < flashCards.length; i++){
      if(flashCards[i] === nameToFind){
          return i
  return -1

console.log(linearSearch(flashCards, "Samuel"))

// Output: 2
// Samuel is at the 2nd index of the flashCards array
Enter fullscreen mode Exit fullscreen mode

Top comments (0)