Linear Search
In C Programming, we looked at the problem of finding a
specified value in an array. The basic strategy was:
Look at each value in the array and compare it to what we're
looking for. If we see the value at any time, return that we've
found it. Otherwise, if after we're done at looking through each
item in the array, if we still haven't found it, then return that
the value isn't in the array. In code, we have something like
this:
int search(int array[], int len, int value)
{
int i;
for (i=0; i<len; i++) {
if (array[i] == value)
return 1;
}
return 0;
}
Clearly, for an unsorted array, this algorithm is optimal.
There's no way you can definitively say that a value isn't in the
array unless you look at every single spot. (Similarly, there's
no way you can say that you DON'T have some piece of paper
or form unless you look through ALL of your pieces of paper.)
But, we might ask the question, could we find an item in an
array faster if it were already sorted?
This preview has intentionally blurred sections. Sign up to view the full version.
View Full DocumentBinary Search
Consider the following game you most likely played when you
were a child:
I have a secret number in between 1 and 100. Make a guess
and I'll tell you whether your guess is too high or too low. Then
you guess again. The process continues until you guess the
correct number and your job is to minimize the number of
This is the end of the preview.
Sign up
to
access the rest of the document.
 Fall '09
 Guha
 Computer Science, C Programming, Searching, Array, 1 k, Search algorithm

Click to edit the document details