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;
}
Here is the problem:
if(item==arr[mid])
return mid;
else if(item<arr[mid])
low=mid+1;
else
up=mid-1;
just change the conditon of choosing low
and up
index according the value of mid index arr[mid]
like:
if(item==arr[mid])
return mid;
else if(item<arr[mid])
up=mid-1;
else
low=mid+1;
OR change this condition else if(item<arr[mid])
into else if(item > arr[mid])
and your code will work fine.
if(item==arr[mid])
return mid;
else if(item > arr[mid])
low=mid+1;
else
up=mid-1;
NB: while(low<=up && item!=arr[mid])
in this line, you're using mid
in arr[mid]
before it has been assigned a value, resulting in Undefined Behavior. (Also, the && item!=arr[mid]
part of the while test is unnecessary.) Credit: 1201ProgramAlarm
The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.