Loading...
The simplest search algorithm that examines each element sequentially until the target is found or the entire array is searched.
Linear time in worst case
Constant extra space
Element at first position
Not applicable to searching
def linear_search(arr, target):
"""
Linear Search Algorithm
Time Complexity: O(n)
Space Complexity: O(1)
"""
for i in range(len(arr)):
if arr[i] == target:
return i # Return index if found
return -1 # Return -1 if not found
# Example usage
array = [64, 34, 25, 12, 22, 11, 90, 88, 76, 50]
target = 22
result = linear_search(array, target)
if result != -1:
print(f"Element {target} found at index {result}")
else:
print(f"Element {target} not found")