Linear search

suggest change

Linear search is a simple algorithm. It loops through items until the query has been found, which makes it a linear algorithm - the complexity is O(n), where n is the number of items to go through.

Why O(n)? In worst-case scenario, you have to go through all of the n items.

It can be compared to looking for a book in a stack of books - you go through them all until you find the one that you want.

Below is a Python implementation:

from collections.abc import Iterable
from typing import TypeVar

T = TypeVar("T")


def linear_search(values: Iterable[T], query: T) -> bool:
    for value in values:
        if query == value:
            return True
    return False

print(linear_search(["apple", "banana", "carrot", "fig", "garlic"], "fig"))
True

Feedback about page:

Feedback:
Optional: your email if you want me to get back to you:



Table Of Contents