Here is my code.The code is running but not getting the right results. For ex- searching 3 in the program is getting output "not found" even though present.
#include<stdlib.h>
#include<iostream>
using namespace std;
int Bsearch(int arr[],int item,int n)
{
int low,mid,up;
low=0;up=n-1;
while(low<=up && item!=arr[mid])
{
mid=(low+up)/2;
if(item==arr[mid])
return mid;
else if(item<arr[mid])
low=mid+1;
else
up=mid-1;
}
return -1;
}
int main()
{
int index,item;;
int arr[]={1,2,3,4,5,6,7,8,9};
cout<<"enter search item\n";
cin>>item;
index=Bsearch(arr,item,9);
if(index!=-1)
cout<<"element found at position"<<(index+1);
else
cout<<"element not found";
return 0;
}
Aucun commentaire:
Enregistrer un commentaire