I am working on an assignment for my class and the goal of this function is to use Binary Sort on an array of a struct, and return the index of the very first location that a last name is found (even if there are multiple last names, just return the first one). My code works almost perfectly for what I am trying to do, but when I print the index, the output I am getting is 1 too many. For example, if I call my function like this with the string "Zulauf" as the last name:
cout << binaryFindFirstByLastName("Zulauf", person, total) << endl;
I get 99811 instead of its actual location of 99812 (this is obviously reading from a large file). Any help or general advice would be greatly appreciated, thank you!
int binaryFindFirstByLastName(const std::string& value, const Person* array, int size) {
int low = 0;
int high = size-1;
int mid = (low + high) / 2;
while (low + 1 != high) {
mid = (low + high) / 2;
if (array[mid].last < value) {
low = mid;
}
else {
high = mid;
}
mid = (low + high) / 2;
}
if (high > size || array[high].last != value) {
return -1;
}
else return high;
}