I'm trying to write a function which takes an array of integers & searches the part of the array between the first and last for the given value. If the value is in the array, return that position. If it is not, I want to return -1.
Here is the code for my function.
int binarySearch(int *array, int min, int max, int value) {
int guess = 0;
bool found = false;
while (!found) {
guess = ((array[min] + array[max]) / 2);
if (array[guess] == value) {
found = true;
return guess;
}
else if (array[guess] < value) {
min = guess + 1;
}
else if (array[guess] > value) {
max = guess - 1;
}
}
return -1;
}
I'm unsure how to break out of the while loop when the value you are searching for is not in the array? This is the pseudocode I am following for implementing a binary search function :
- Let min = 0 and max = n-1(array size -1 ). Compute guess as the average of max and min, rounded down (so that it is an integer).
- If array[guess] equals target, then stop. You found it! Return guess.
- If the guess was too low, that is, array[guess] < target, then set min = guess + 1.
- Otherwise, the guess was too high. Set max = guess - 1.
- Go back to step 2.