Share my recursive binary search c++ implementation


  • 0
    J

    class Solution {
    public:
    int findMin(vector<int> &num) {
    if(num.size() == 1)
    return num[0];
    if(num[0] < num[num.size()-1])
    return num[0];
    return binary_search(num, 0, num.size()-1, num[0]);
    }

    int binary_search( vector<int> &num, int low, int high, int key){
        
        if(low>high)
            return -1;
        if(high - low ==1)
            return num[low] > num[high]?num[high]:num[low];
       int mid = low+(high-low)/2; 
       if(num[mid]>num[mid+1])
            return num[mid+1];
       if(num[mid] < key)
              return binary_search(num,low,mid,key);
        else
              return binary_search(num,mid,high,num[mid]);
    }
    

    };


Log in to reply
 

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