###Linear search - Traverse each element to check for a match
Linear search can be implemented upon almost any types of iterable, whether it be array, list, linked-list, etc.
LINEAR_SEARCH(ITERABLE L, element_to_search):
FOR i = L.FIRST TO L.LAST:
IF L[i] == element_to_search:
RETURN i
END IF
END FOR
RETURN FALSE
END LINEAR_SEARCH
Start iterating over the elements.
If a match is found at index i, return this index to indicate that the element exists at index i
.
If the loop reaches the last element, we can conclude that no matching elements have been encountered. In that case return false
.
Since every elements are visited individually, complexity can be coined as O(n).
However if the element is located at starting index, it would be our best case scenario resulting in O(1). The worst case is when the element doesn't even exist or if it does, it exists at the last index. The loop will be iterating over the complete list making it an O(n).