I am trying to implement a binary search using a while
loop. It seems to work when the int
I am looking for is in the array; however, when the int
I am searching for is not there, the program seems to get stuck in the loop, without returning false. I have been using the gdb, but I still can't seem to figure out the bug. As you can see, I have maybe added a bunch of extra if statements, etc. trying to figure this out.
bool search(int value, int values[], int n) {
sort(values, n);
int begin = 0;
int end = (n - 1);
if (n < 1) {
return false;
}
while (end > begin + 1) {
int center = ((begin + end) / 2);
if (values[0] == value) {
return true;
}
if (begin == value) {
return true;
}
if (end == value) {
return true;
}
if (end == (begin + 1) || end == begin) {
if (end == value || begin == value) {
return true;
} else {
return false;
}
}
if ((values[center]) == value) {
return true;
} else
if ((values[center]) > value) {
end = center;
} else
if ((values[center]) < value) {
begin = center;
} else {
return false;
}
}
// TODO: implement a searching algorithm
return false;
}