<aside> <img src="/icons/table_red.svg" alt="/icons/table_red.svg" width="40px" /> Table of Contents
</aside>
<aside> 💡
<aside> 💡
Searching Algorithms
Linear Search
Algorithm for Linear Search
Input: Array $A$ of size $n$, key $x$.
Output: Index of $x$ if found; otherwise, -1.
For $i = 0$ to $n-1$:
Return -1.
Python Code for Linear Search
def linear_search(arr, key):
for i in range(len(arr)):
if arr[i] == key: # Compare each element
return i # Return the index if found
return -1 # Return -1 if not found
Time Complexity of Linear Search
Let $n$ be the number of elements.
For $n$ elements, the total comparisons in the worst case are:
$$ T(n) = n \quad \implies \quad O(n). $$