I have a working binary search function that asks a to user input a name and it will search for it in the Student array structure and display the corresponding average GPA for that student. It will keep looping for the user to enter in a name to search for unless the user enters in a period.
The problem I have is the break
statement I am using. The requirements for this function that I need to follow does not allow me to use a break
statement.
However, if I remove the break
statement, my binary search will infinitely print out the output statement and will not work properly anymore.
Is there a way for me to work around this and not use a break
statement? I have a feeling I could be using several if
statements instead of the break
statement.
void binarySearch(Student* ptr, int MAXSIZE)
{
string target;
string period = ".";
int first = 0,
last = MAXSIZE - 1,
mid;
do
{
cout << "Enter student name (Enter . to stop): ";
cin >> target;
while (first <= last)
{
mid = (first + last) / 2;
if (ptr[mid].name.compare(target) == 0)
{
cout << "Student " << target << " :gpa " << ptr[mid].avg << endl;
first = 0;
last = MAXSIZE - 1;
break; // I am stuck on making the binary search work without using this break statement
}
else if (ptr[mid].name.compare(target) < 0)
last = mid - 1;
else
first = mid + 1;
}
if (first > last && target.compare(period) != 0)
{
cout << "This student was not found. Enter another name" << endl;
first = 0;
last = MAXSIZE - 1;
}
} while (target.compare(period) != 0);
}
Aucun commentaire:
Enregistrer un commentaire