You're right there is a very simple little error. The strcmp()
return value comparison is greater than 0 when the first string is greater than the second string. Which means that your comparisons should be flipped.
Here is the fixed code:
int AccountDB::searchForAccount(char* searchNumber)
{
int low = 0;
int high = accountsAmount - 1;
int mid;
//now for the loop, using strcmp because these are C strings
while (low<=high)
{
mid = (low + high) / 2;
if (strcmp(searchNumber,credArray[mid].getAccountNumber()) == 0)
return mid;
if (strcmp(searchNumber,credArray[mid].getAccountNumber()) < 0) // this is now "<"
high = mid -1;
else
low = mid + 1;
}
return -1;
}
Update: Small Optimisation
Consider making this change to make it run a little faster, it's also easier to read.
while (low<=high)
{
mid = (low + high) / 2;
int val = strcmp(searchNumber,credArray[mid].getAccountNumber());
if (val == 0)
return mid;
if (val < 0)
high = mid -1;
else
low = mid + 1;
}