I need to guess a number. I can only see if the number I\'m proposing is lower or higher. Performance matters a whole lot, so I thought of the following algorithm:
Le
yes binary search
is the most effective way of doing this. Binary Search
is what you described. For a number between 1 and N Binary Search
runs in O(log(n))
time.
So here is the algorithm to find a number between 1-N
int a = 1, b = n, guess = average of previous answers;
while(guess is wrong) {
if(guess lower than answer) {a = guess;}
else if(guess higher than answer) {b = guess;}
guess = (a+b)/2;
} //Go back to while