Reputation: 1679
Would you please help me with this simple code in C++, I don't know what is the problem here?
#include <iostream>
#include <string>
using namespace::std;
template <class Type>
Type binsearch (Type item,Type *table,Type n)
{
int bot=0;
int top=n-1;
int mid, cmp;
while (bot<= top)
{
mid=(bot+top)/2;
if(item==table(mid))
return (mid);
else if (item <table[mid])
top=mid-1;
else
bot=mid+1;
}
return -1;
}
int main ()
{
int nums[]={10, 12, 30, 38, 52, 100};
cout<< binsearch(52, nums, 6);
}
Upvotes: 0
Views: 1550
Reputation: 505
It has to be
if(item==table[mid])
not
if(item==table(mid))
Upvotes: 1
Reputation: 39099
Problem is that you are confusing the [
and (
. Instead of
---
mid=(bot+top)/2;
if(item==table(mid))
return (mid);
---
you need
+++
mid=(bot+top)/2;
if(item==table[mid])
return (mid);
+++
Upvotes: 1
Reputation: 133072
if(item==table(mid))
should be
if(item==table[mid]) //notice square brackets []
^ ^
Upvotes: 0