14C. More on Search Algorithms


Search algorithm requirement

In your programming assignment submissions, you are required to use a search algorithm to solve a search problem.

The following is an example of what not to do. Suppose that you want to know whether the first n numbers in array A are all positive. One way to do that is to count the number of positive values and ask if that count is equal to n. Here is an implementation of that idea.

  bool allPositive(const int A[], const int n)
  {
    count = 0;
    for(int i = 0; i < n; i++)
    {
      if(A[i] > 0)
      {
        count++;
      }
    }
    return (count == n);
  }

That gets the right answer, but it needs to look at every number, no matter what. If you think of it as a search problem, allPositive(A, n) is responsible for searching for a number that is not positive. As soon as it sees one, the answer is obvious. You only need to look at all n numbers if they are all positive, or if only the last number is not positive. We have seen a definition of allPositive as a search algorithm.


A common error

When writing function definitions, you always need to stay alert and keep your thinking cap on. Sometimes beginners program just by throwing things onto paper or a computer screen, and end up with something like this faulty definition of allPositive.

  bool allPositive(const int A[], const int n)
  {
    count = 0;
    for(int i = 0; i < n; i++)
    {
      if(A[i] <= 0)
      {
        return false;
      }
      else
      {
        return true;
      }
    }
    return true;
  }

Here, the student has reasoned (superficially): The function returns false if A[i] ≤ 0, so it should return true if A[i] > 0. That reasoning is clearly incorrect, and a quick inspection shows that. Notice that the body of the loop always returns. That means it is not possible to perform the loop body more than once. The answer is determined by looking at A[0], and only A[0]. How can you tell if all of the values in an array are positive if you only look at one of those values, no matter what?

Watch out for this error. It is surprisingly common.