Linear Search
Algorithms
Linear search is a simple search algorithm that checks each element in the array sequentially until the target element is found or the entire array has been searched.
Algorithm
The algorithm iterates through the array from the beginning, comparing each element with the target value until a match is found or the end of the array is reached.
Time Complexity
Linear search has a time complexity of , where is the number of elements in the array.
Implementation
def linear_search(arr, target):
for index, value in enumerate(arr):
if value == target:
return index
return -1 # Return -1 if the target is not found
# Example usage with different numbers
arr = [45, 23, 78, 12, 56, 89, 34]
target = 56
result = linear_search(arr, target)
if result != -1:
print("Element {} found at index {}.".format(target, result))
else:
print("Element {} not found in the array.".format(target))