The linear search algorithm is a simple and straightforward searching algorithm used to find a specific element within a list or array. It works by iterating through each element of the list sequentially until the target element is found or the end of the list is reached.
Let's consider the following list of numbers:
[5, 12, 3, 7, 1, 9]
We want to search for the number 7
using a linear search.
5
) with 7
. They don't match.12
) and compare it with 7
. They don't match.7
.7
and returns its position (index), which is 3
.function linearSearch(list, target) {
for (let i = 0; i < list.length; i++) {
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 the time it takes to search the list grows linearly with the number of elements. In the worst case, the algorithm has to check every element in the list before finding the target element or determining that it's not present.
The linear search algorithm is a basic but useful searching technique that can be applied to any list or array. While it is simple to implement, it's important to consider its time complexity and limitations, especially for large datasets. For sorted lists, more efficient algorithms like binary search should be considered.
Create a customised learning path powered by AI — stay focused, track progress, and earn certificates.
Build Your Learning Path →