Reputation: 109
I made a simple sequential search function, so as i'm testing it, if I put 25 into my search item it returns true, but the other numbers 90, 21 are always false and I can't understand why it's doing that.
int a[] = {25,90,21};
int searchItem = 90;
if(sequentialSearch(searchItem, a, 3) == 1)
{
cout << "Found Item" << endl;
}
else
{
cout << "Item Not Found" << endl;
}
bool sequentialSearch(int searchItem, int * a, int size)
{
for(int i = 0; i < size; i++)
{
if(searchItem == a[i])
{
return true;
}
else
{
return false;
}
}
}
Upvotes: 3
Views: 507
Reputation: 634
Your for loop ends up only checking the first item, and then returning true or false. You need to change your logic to do something like
for( . . . )
{
if(searchItem == a[i]) return true;
}
return false;
This way it will test each item in the array and then return false if nothing found.
Upvotes: 3
Reputation: 851
you return false if your element is not at first position. Try this
bool sequentialSearch(int searchItem, int * a, int size)
{
for(int i = 0; i < size; i++)
{
if(searchItem == a[i])
{
return true;
}
}
return false;
}
Upvotes: 8