Easy binary search approach in C++


#1
vector<int> Solution::searchRange(const vector<int> &A, int B) 
{
    int j=A.size()-1,i=0,left=-1,right=-1;
    //search for the left index
    while(i<=j)
    {
        int mid=(i+j)/2;
        if(A[mid]==B)
        {
            // Left index will be found if mid is the 0th index or
            // A[mid]==B and the element before the mid index is less than B
            if((mid>0 && A[mid-1]<B) || (mid==0))
            {
                left=mid;
                break;
            }
            else
            {
                j=mid-1;
            }
        }
        else if(A[mid]>B)
        {
            j=mid-1;
        }
        else
        {
            i=mid+1;
        }
    }
    //Search for the right index
    i=0,j=A.size()-1;
    while(i<=j)
    {
        int mid=(i+j)/2;
        if(A[mid]==B)
        {
            // Right index will be found if mid is the (n-1)th index or
            // A[mid]==B and the element after the mid index is greater than B
            if(mid==A.size()-1 || (mid<A.size()-1 && A[mid+1]>B))
            {
                right=mid;
                break;
            }
            else
            {
                i=mid+1;
            }
        }
        else if(A[mid]<B)
        {
            i=mid+1;
        }
        else
        {
            j=mid-1;
        }
    }
    return {left,right};
}