Linear search
suggest changeLinear 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
Found a mistake? Have a question or improvement idea?
Let me know.
Table Of Contents