Linear Search Algorithm in Python
Linear search is a simple search algorithm that sequentially checks each element of an array until it finds the target value or until all elements have been checked. This method is straightforward but can be inefficient for large arrays since every element must be checked one by one.
Example: Linear Search
The following code demonstrates how to implement a linear search to find a specific value in an array.
def search(arr, n, x): # Traverse through the array for i in range(n): if arr[i] == x: return i return -1 # Searching for the character 'D' in the array arr = ['A', 'B', 'C', 'D', 'E'] x = 'D' n = len(arr) # Function call result = search(arr, n, x) if result == -1: print("Element is not present in the array") else: print("Element is present at index", result)
Output:
Element is present at index 3
In this example, the function checks each element in the array arr
until it finds the target element D
. When it finds the match, it returns the index of the element. If the element is not found, the function returns -1
.