2

I am writing two functions, the first one does a linear search and is supposed to return the position of the first found value if it is in the vector. The second method is a binary search that is done using equal_range and it is supposed to return the same thing as the linear search. Currently they are checking every value as a match. Any help is appreciated.

int linearSearch( const vector<int>& vec, int z)
{
   vector<int>::iterator iter = find(vec.begin(), vec.end(), z);

   if (iter != vec.end())
      return (iter-vec.begin());

   else
      return -1;
}

int binarySearch( const vector<int>& vec, int z)
{
    pair<vector<int>::const_iterator, vector<int>::const_iterator> bounds;

    bounds = equal_range(vec.begin(),vec.end(), z);

    if (bounds.first != vec.end())
       return (bounds.first -vec.begin());

    else
       return -1;
}
jkdev
  • 11,360
  • 15
  • 54
  • 77
GrapeSoda3
  • 583
  • 1
  • 7
  • 17

1 Answers1

1

Your description is unclear, but I'll point out some concerns with the code.

In binarySearch() search, there is

bounds = equal_range(vec.begin(),vec.end(), z);

if (bounds.first != v.end())
   return (bounds.first -v.begin());

v is not declared anywhere. If the code compiles then, presumably, it is declared somewhere in code you haven't shown. But it may have no relationship to vec. The behaviour of the code (particularly the return) will be undefined.

A rather fundamental difference between the functions is because std::equal_range() assumes a sorted (or partitioned) range, and std::find() does not.

Peter
  • 35,646
  • 4
  • 32
  • 74