The Linear Search Algorithm
The idea of this search is simply to look at each value in succession to see if it is the one you are looking for, until you find what you are looking for, or until you have no more values to look at.
Name: SearchLinear
Input:
Output:
Algorithm SearchLinear(sequence, targetValue, firstPosition, lastPosition,
targetPosition, targetFound)
--------------------------------------------------------------------------
Make sequence value at first position of search range the current value
while position of current value remains valid and current value not target value
Make value at next position the current value
endwhile
if position of current value is still valid, target value is at that position
This particular version of the algorithm assumes nothing at all about the data. It can be improved somewhat for particular sequence instances if the data is known to be sorted, but this will not affect (improve) the overall performance of the algorithm. Note that the algorithm finds the first value that's equal to the one you're looking for and is located within the search range. There may be additional instances of the target value in that range, which can be found by applying the same algorithm to an appropriately adjusted search range.
We say that the linear search algorithm is, in general, a O(n) algorithm, or that it has "linear time complexity".
target value in position .................... 1 2 3 ... n number of comparisons required to find it ... 1 2 3 ... nFrom this is follows that the average number of comparisons is thus
1 + 2 + 3 + ... + n n(n+1)/2
------------------- = -------- = (n+1)/2 or n/2 + 1/2
n n
and n/2 + 1/2 is O(n).