0

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;
}
Remy Lebeau
  • 555,201
  • 31
  • 458
  • 770
shishank98
  • 23
  • 6
  • 1
    It is also useful to tell us if the program terminates. – Allan Wind Dec 27 '20 at 08:31
  • If you search for [c++] binary search you this https://stackoverflow.com/questions/446296/where-can-i-get-a-useful-c-binary-search-algorithm and this might be a good resource for you too https://stackoverflow.com/questions/18774858/using-binary-search-with-vectors – Allan Wind Dec 27 '20 at 08:33

2 Answers2

3

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;
Jarvis
  • 8,494
  • 3
  • 27
  • 58
0

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; 
}
Remy Lebeau
  • 555,201
  • 31
  • 458
  • 770
Shreesh
  • 1
  • 2