Guessing a number knowing only if the number proposed is lower or higher?

前端 未结 7 950
悲哀的现实
悲哀的现实 2021-01-02 21:34

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

7条回答
  •  心在旅途
    2021-01-02 22:20

    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
    

提交回复
热议问题