1.6 Case study: Searching in a list

If you want to find the position in an unsorted array of nn objects that stores a particular value, you cannot really do better than simply looking through the array from the beginning and moving toward the end until you find what you are looking for. This algorithm is called sequential search. If you do find it, we call this a successful search. If the value is not in the array, eventually you will reach the end. We will call this an unsuccessful search. Here is a simple implementation for sequential search.

// Return the position of an element in an array A.
// If the element is not found, return `null`.
function sequentialSearch(arr, val) -> Int:
    for i in 0 .. arr.size - 1:   // For each element in A,
        if arr[i] == val:         // if we found it
            return i              // return this position.
    return null                   // Otherwise, return null

It is natural to ask how long a program or algorithm will take to run. But we do not really care exactly how long a particular program will run on a particular computer. We just want some sort of estimate that will let us compare one approach to solving a problem with another. This is the basic idea of algorithm analysis. In the case of sequential search, it is easy to see that if the value is in position ii of the array, then sequential search will look at ii values to find it. If the value is not in the array at all, then we must look at all array values. This would be called the worst case for sequential search. Since the amount of work is proportional to the size of the array, we say that the worst case for sequential search has linear cost. For this reason, the sequential search algorithm is sometimes called linear search.