Simple Java binary search using both iterative and recursive


  • 0
    L
    public int guessNumber(int n) {
           int s = 1;
            int e = n;
            while(e>=s) {
                int p = (e-s)/2 + s;
                int result = guess(p);
                if(result==0) {
                    return p;
                }
                else if(result>0) {
                    s=p+1;
                }
                else {
                    e=p-1;
                }
            }
            
            return e;
    }
    
    public int guessNumber(int n) {
            return helper(1,n);
        }
        
        private int helper(int s, int e) {
            if(e<s) {
                return e;
            }
            int p = (e-s)/2 + s;
            int result = guess(p);
            if(result==0) {
                return p;
            }
            return result>0?helper(p+1,e):helper(s,p-1);
        }
    

Log in to reply
 

Looks like your connection to LeetCode Discuss was lost, please wait while we try to reconnect.