Linear search: Difference between revisions
From Coderwiki
More actions
new |
(No difference)
|
Revision as of 11:38, 9 August 2025
A linear search is a search algorithm which simply steps through each element of an array or list and checks if it matches the target value.
Advantages of a linear search
- Faster than a binary search on very small datasets
- Very easy to implement
- The array or list does not need to be in order
Disadvantages of a linear search
- Almost always slower than a binary search
Example: linear search in Python
This will print the index of the first instance of the number 9 in the list.
It would make more sense to use Python's enumerate method here, but we don't use it as it is not necessarily found in other languages (and this wiki aims to be as generic as possible).
data = [3, 4, 7, 9, 1, 2, 9, 12]
target = 9
for i in range(len(data)): # loop over indices of data list
element = data[i] # get the element at the current index
if element == target: # check if element matches target
print(i) # print index of first occurance
break # stop after first instance