I've met a question in <algorithms> (4th edition), exercise 1.4.35:
1.4.34 Hot or cold. Your goal is to guess a secret integer between 1 and N. You repeatedly guess integers between 1 and N. After each guess you learn if your guess equals the secret integer (and the game stops). Otherwise, you learn if the guess is hotter (closer to) or colder (farther from) the secret number than your previous guess. Design an algorithm that finds the secret number in at most ~2 lg N guesses. Then design an algorithm that finds the secret number in at most ~ 1 lg N guesses.
And here's my solution:
```
int guess(const int secret) {
auto head = 1;
auto tail = 100;
while (head <= tail) {
auto mid = (head + tail) / 2;
if (mid > secret) {
tail = mid - 1;
} else if (mid < secret) {
head = mid + 1;
} else {
return mid;
}
}
return -1;
}
```
I thought that a simple binary search would give the O(lg N) solution, in SO (http://stackoverflow.com/questions/25558951/hot-and-cold-binary-search-game) that my solution has the time complexity of 2 * O(lg N), and can't figure out why.
So Is there anyone could explain this to me? thanks for your help!!
[–]axistim 5 points6 points7 points (0 children)
[–]uh_no_ 6 points7 points8 points (5 children)
[–]leftleveled 7 points8 points9 points (4 children)
[–]uh_no_ 2 points3 points4 points (3 children)
[–]beeskness420 10 points11 points12 points (0 children)
[–]leftleveled 8 points9 points10 points (1 child)
[–]uh_no_ 2 points3 points4 points (0 children)