lundi 29 janvier 2018

binary search fuction always returns -1 value instead of index

My Binarysearch function returns -1 always instead of index even if the data is present in the array.Can anyone please help me in figuring out the problem

int main(){

int ar[10]={1,2,3,4,5,6,7,8,9,10};
int i,w;
cout<<"enter the element to search"<<endl;
cin>>w;
int y  = binarysearch(ar,w,0,9);
cout<<y<<" index"<<endl;
return 0;
}

int binarysearch(int ar[],int x,int p,int r)
{

    int q;
    if(p==r)
    {
        if(ar[r]==x)
            {
                return r;
            }
        else
           {
                return -1;
           }
    }
    else{
        q = ((r+p)/2);
          if(x<ar[q])
             {
                 return(binarysearch(ar,x,p,q));
             }
              else
                return(binarysearch(ar,x,q+1,r));
}


}

Aucun commentaire:

Enregistrer un commentaire