Search code examples
c++binary-search

Why isn't my binary search giving me a result for the first element?


I'm trying to return the index of the element to be searched. All the elements are being detected except the first element. What's wrong? Why is the function not returning index 0?


using namespace std;
int binsearch(int a[],int x,int y)
{
    int low=a[0];
    int high=a[x-1];
    while(low<=high)
    {
        int mid=(low+high)/2;
        if(y==a[mid])
        {
            return mid;
        }
        else if(y>a[mid])
        {
            low=mid+1;
        }
        else
        {
            high=mid-1;
        }
    }
    return -1;
}
int main()
{
    int a[]={1,2,3,4,5,6,7,8,9};
    int x=sizeof(a)/sizeof(a[0]);
    int y;
    cin>>y;
    cout<<binsearch(a,x,y);
}

Solution

  • int low=a[0];
    int high=a[x-1];
    

    should be

    int low=0;
    int high=x-1;