Implementing strictly lower_bound in C/C++

I have come up with this solution to implement strictly lower bound in a sorted array:

long lowerBound(long key, long size, long *a){
    long low = 0, high = size, mid;
    if(a[low] >= key){
        return -1;
    }
    while(low < high){
        mid = (low+high)/2;
        if(a[mid] >= key){
            high = mid - 1;
        } else{
            low = mid;
        }
    }
    return low;
}

But this does not seem to work. It fails at some test cases. Can anyone point me in right direction. Thanks in advance!!

long lowerBound(long key, long size, long *a){
long low = 0, high = size - 1, mid, ans;
if(a[low] >= key){
return -1;
}
while(low <= high){
mid = (low+high)/2;
if(a[mid] >= key){
ans=mid;
high = mid - 1;
} else{
low = mid + 1;
}
}
return ans;
}

1 Like