Linear Search

Linear search, also known as sequential search — an algorithm for finding a given value of an arbitrary function on some interval.

Algorithm:

Example:

Consider an example where we have a list of numbers and we are looking for the number 3:

Thus, the result of the function execution will be Some(3), meaning the element has been found. If we were looking for, say, the number 6, the function would continue calling itself until it reached an empty list and would ultimately return None.

Estimation:

Code:

@tailrec
def linearSearch[A](list: List[A], key: A): Option[A] =
  list match
    case Nil                      => None
    case head :: _ if head == key => Some(key)
    case _ :: tail                => linearSearch(tail, key)

val text   = "This is a functional implementation."
linearSearch(text.toList, 'a')
// Some(a)

Links: