The linear search algorithm
Linear search (or sequential search) is a simple algorithm for searching a target value in arrays and lists. The algorithm checks each element of the array until it finds an element that matches the target value. If the algorithm reaches the end of the array, it terminates unsuccessfully.
In the worst cases, it performs exactly N
comparisons where N
is the length of the input sequence of elements. The time complexity is O(N)
.
How does it work by example
How does it work by example
Suppose, we have an array with six elements:
Our goal is to search for the index of an element that equals 20. We will start from the first element with the index 0 and compare each element of the array with the target value until we find the appropriate element.
Possible modifications of the linear search
Even such a simple algorithm has various small modifications:
- checking the array contains a specified element, the result is true or false;
- searching the first/the last occurrences of an element in the array;
- counting all occurrences of an element in the array;
- searching all occurrences of an element in the array;
- searching a value only in a range of indexes of the array.