DEV Community

Tommy
Tommy

Posted on

2

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.

ex:
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)

AWS Security LIVE!

Join us for AWS Security LIVE!

Discover the future of cloud security. Tune in live for trends, tips, and solutions from AWS and AWS Partners.

Learn More

👋 Kindness is contagious

Please leave a ❤️ or a friendly comment on this post if you found it helpful!

Okay