Reputation: 15
I am trying to write code for a binary search, but it is not showing any output. Please tell me my errors.
#include <iostream>
using namespace std;
int main(){
int a[]= {1, 3, 5 , 7, 32};
int n;
cin>>n;
int last=(sizeof(a)/sizeof(a[0]))-1;
int first=0;
while(first<=last){
int mid=(last-1)/2;
if(a[mid]==n){
cout<<"No. Found"<< endl;
}
if(n>a[mid])
{
first=mid+1;
}
else
{
last=mid-1;
}
}
cout<<"Not Found"<<endl;
return 0;
}
Upvotes: 0
Views: 483
Reputation: 1
The reason why your code for binary search is not producing any output because there are some logical errors like:
You are using an incorrect method to find the mid-value, the appropriate method to find the mid value is :
mid = (f1 + f2) / 2** (where f1 = first, f2 = last)
Here is the code for the updated binary search with some helpful comments:
#include <bits/stdc++.h>
using namespace std;
// A Iterative Binary Search Function.
int BinarySearch(int arr[], int low, int r, int x)
{
while (low <= r)
{
int mid = low + (r - low) / 2;
// To check whether int x is at mid or not.
if (arr[mid] == x)
{
return mid;
}
// If x is greater than mid value, ignore the left half
if (arr[mid] < x)
{
low = mid + 1;
}
// If x is smaller than mid-value, ignore the right half
else
{
r = mid - 1;
}
}
// if your desired element is not there
return -1;
}
int main(void)
{
int arr[] = {1, 3, 5, 7, 32};
int x;
cin >> x;
int n = sizeof(arr) / sizeof(arr[0]);
int result = binarySearch(arr, 0, n - 1, x);
if(result == -1)
{
cout << "Element is not present in array"
cout << "Element is present at index " << result << endl;
}
return 0;
}
Upvotes: 0
Reputation: 8564
The way you calculate mid
is wrong, it should be this:
int mid = (first + last) / 2;
Preferable way is this to avoid overflow (first + last
can overflow) :
int mid = first + (last - first) / 2;
or with >>
operator:
int mid = (first + last) >> 1;
Upvotes: 3