Hello, I am having troubles using binary search to find a name in an array, when compared to a user entered name. Any hints or tips would be greatly appreciated!
void search(int entries, item person[], int size)
{
char searched[30];
int j, low, high;
int flag_found(0);
//cls;
printf("Please enter name to look for: ");
gets(searched);
low=1;
high= entries-1;
flag_found=0;
do
{
j = ((low + high)/2);
if(strcmp(person[j].name,searched) > 0)
{
flag_found = 1;
}
else
{
if (person[j].name > searched)
{
high = j - 1;
}
else
{
low = j + 1;
}
}
}while ((low <= high) && (flag_found == 0));
if(flag_found==1)
{
cls;
cout<<"Here is the person you asked for: \n\n";
cout<<"\t Name\t\t\t\tMark 1 Mark 2\t\tAverage\n";
cout<< "\t" << person[j].name
<< "\t\t\t\t " << person[j].mark1
<< "\t " << person[j].mark2
<< "\t\t " << person[j].average;
cout<<endl;
pause;
}
else
{
cls;
cout<<endl;
cout<<"Name entered was not found in database!";
cout<<endl;
pause;
}
When I search for a name that is within the array, it will either say name not found, or return a name that i did not search for. Again any hints where I went wrong would be much appreciated.
I think the problem occurs between lines 19 and 39 in my do while loop.
Doesn't make any sense. if you compare two cstrings, you compare their memory addresses. Also, even if it did work, it would only work if the name array is alphabetically sorted. (if the array IS indeed alphabetically ordered, use strcmp here).
My program does have an alphabetical sort function, and analyzing my teacherd .exe file, I've realized he has alphabetically sorted them before searching.
That's because your corrections are not correct. The if before the flag_found should be true if strcmp returns 0 (if you look in my example, you will see that I use the ! operator in front of strcmp to negate it's boolean value- in C++ 0 is false and all other numbers are true), the if before high = j -i should check if strcmp returns >0.