二分查找

class BinarySearch {
public:
    int getPos(vector<int> A, int n, int val) {
        // write code here
      
        if(n==0)
            return -1;
        else
            return find(A,0,A.size(),val);
     }
   
    int find(vector <int> A,int a,int b,int val)
        {
         int low=a;
         int high=b;
          if(low>high)
              return -1;
          else
               {
                int mid=(high+low)/2;
                if(A[mid]==val)
                    return mid;
                else
                    {
                     if(A[mid]>val)
                       return find(A,mid+1,high,val);
                    else
                       return find(A,low,mid-1,val);
                    }    
               }      
    }
   
};

posted @ 2017-03-21 19:11  爱编程的小羊  阅读(126)  评论(0编辑  收藏  举报