Let's apply a linear search algorithm and write a function to carry it out. Our function will take three arguments: the array to search, the number of elements in the array, and a value to search for. The function will return the index into the array that the value was found at, or -1 if the value wasn't found (remember that in programming languages like C, C++, and Java, arrays of length N have indices numbered 0 through N-1; therefore a return value of -1 cannot be valid place in the array and the calling function will know that the value wasn't found).
We declare our function as follows:
Step 1: We need to search through every element in the array. This can be easily accomplished using a loop.
Step 2: At every place in the array, we need to compare the array element to the value we're searching for. If this index stores the value, then immediately return the correct answer. Otherwise, keep going.
Step 3: What happens if the value is never found? The loop will end and the function will continue. So after the loop we need to return the value -1.
Step 4: Putting this all together we end up with a function to do a linear search of an array:
Sequential search has some advantages over other searches. Most importantly, it doesn't require the array to be sorted, since every array element is examined. In addition, linear search is quite easy to implement, as evidenced by the relative simplicity of the code above. The disadvantage of sequential search is efficiency. Since this approach examines every element in the list, it does work for every element. Therefore, linear search is O(n), relatively inefficient, as sorting algorithms go.