The linear search algorithm is a fundamental searching technique used to find a specific element within a list or array. It works by iterating through each element of the list one by one, comparing it with the target element until a match is found.
Let's consider a list of numbers: [5, 12, 3, 8, 1]
and the target element is 8
.
5
. 5
is not equal to 8
, so move to the next element.12
, which is also not equal to 8
. Move to the next element.3
, which is not equal to 8
. Move to the next element.8
, which is equal to the target element. The search is successful, and the index 3
(position of 8
in the list) is returned.function linearSearch(list, target):
for i in range(len(list)):
if list[i] == target:
return i
return -1
The time complexity of linear search is O(n), where n is the number of elements in the list. This means that in the worst case, the algorithm will have to iterate through all n elements before finding the target element or determining that it's not present.
Linear search is a basic searching algorithm that is straightforward to implement but can be inefficient for large lists. It's useful when the list is unsorted or when the list is small enough that the performance difference is negligible. For sorted lists, binary search or other more efficient algorithms are preferred.