I need to search for a string in an array of objects, this is what I have but it does not seem to work, it always gives me the second string in the array instead of the one that i search for.
void binarySearch(Student S[], string name)
{
int first = 0;
int last = 9;
int middle;
int position = -1;
bool found = false;
while(!found && first <last)
{
middle = (first + last)/2;
if(S[middle].getName() == name)
{
found = true;
position = middle;
}
elseif (S[middle].getName() > name)
{
last = middle -1;
}
else
{
first = middle +1;
}
}
cout<<position;
}
void binarySearch(Student S[], string name)
{
int first = 0;
int last = 9;
int middle;
int position = -1;
bool found = false;
//FIRST SORT THE OBJECTS SO THAT THEY CAN BE SEARCHED
Student temp;
bool swap;
do
{
swap = false;
for (int i = 0; i<(10-1);i++)
{
if(S[i].getName() > S[i+1].getName())
{
temp = S[i];
S[i] = S[i+1];
S[i +1] = temp;
swap = true;
}
}
}while(swap);
cout<<"Name Age Average"<<endl;
for (int i = 0; i<10; i++)
{
cout<<left<<setw(25)<<S[i].getName()<<setw(10)<<S[i].getAge()<<setw(10)<<S[i].getAvg()<<endl;
}
//NOW DO THE BINARY SEARCH
while(!found && first <last)
{
middle = (first + last)/2;
if(S[middle].getName() == name)
{
found = true;
position = middle;
}
elseif (S[middle].getName() > name)
{
last = middle -1;
}
else
{
first = middle +1;
}
}
cout<<"Name Age Average"<<endl;
cout<<left<<setw(25)<<S[position].getName()<<setw(10)<<S[position].getAge()<<setw(10)<<S[position].getAvg()<<endl;
}