Linear search algorithm
Linear search is a simple algorithm for finding a target value within a list or array by sequentially checking each element until the target value is found or until all elements have been checked. It has a time complexity of O(n), where n is the number of elements in the list.
Linear search is also known as sequential search, because it looks at each element in the sequence in order.
Linear search is a straightforward algorithm that’s easy to understand and implement, but its performance is not as good as other search algorithms like binary search.
Linear search works on unsorted as well as sorted lists, but when the list is sorted, other algorithms like binary search are faster.
If the target value is not found in the list, the linear search returns a special value, such as -1, to indicate that the target value is not present.
Linear search can be optimized in certain cases, such as if you know that the target value is more likely to occur at the beginning or end of the list. In those cases, you can start the search from the relevant end to save some time potentially.
Linear search is a simple search algorithm that checks every element in a list until it finds the target element or reaches the end of the list. Here’s the Python code:
def linear_search(lst, target):
for i in range(len(lst)):
if lst[i] == target:
return i
return -1
linear_search([1, 2, 3, 4, 5], 5)
The code you provided defines a Python function called linear_search
that takes two arguments: a list (lst
) to search and a target value to find (target
). The function uses a for
loop to iterate over each element in the list and check if the current element is equal to the target value using a if
statement. If the current element matches the target, the function returns the index of that element using the return
statement. If the entire list is searched and the target is not found, the function returns -1 to indicate that the target is not present in the list.
In your example, the function is called with a list [1, 2, 3, 4, 5]
and a target value of 5
. The function should return, which is the index of the element that contains the target value.