int bsearch(int[],int,int);
int main()
{int ar[50],item,n,index;
cout<<"enter desired array size...";
cin>>n;
cout<<"\n enter array elements";
for(int i=0;i<n;i++)
cin>>ar[i];
cout<<"\nenter element to be searcherd for...";
cin>>item;
index=bsearch(ar,n,item);
if(index==-1)
cout<<"\nsorry!!given elment could not found.\n";
else
cout<<"\nelement found at index:"<<index<<",position:"<<index+1<<endl;
return 0;
}
int bsearch(int ar[],int size,int item)
{
int beg,last,mid;
beg=0;
last=size-1;
while(beg<=last)
{
mid=(beg+last)/2;
if(item==ar[mid])
return mid;
else
if (item>ar[mid])
beg=mid+1;
else
last=mid-1;
}
return-1;
}
No comments:
Post a Comment