0

I am a newbie. I wanted to make a binary search function in C++ that didn't take the upper and lower bounds of the array as an arguments. For me, I know the array will be of size 10 no matter what therefore I put r = 9. This code works and took me a while to figure out.

I made this post to ask if there are any better ways to go about this without introducing any new header files. I suspect some of the stuff I did in this code were unnecessary. Can you guys tell me any better ways to write this same function?

#include <iostream>

using namespace std;

void binarySearch(int arr[], int n){

    bool check = false;
    int l = 0;
    int r = 9;
    while (r - l > 0){
        int c;
        int m = (r - l) / 2;
        if (m!=0) m+=l;
        if (m==0 && c==m) m=l+1;
        if (arr[m]==n){
            cout << "Present. \nPostion: " << m+1;
            check = true;
            break;
        }
        else if (arr[m]<n && m!=0) l = m;
        else if (arr[m]>n && m!=0) r = m;
        
        c = m;
    }
    
    if(!check){
        cout << "Absent.";
    }
    
    
}

int main()
{
    int arr[10] = {5,15,25,35,45,55,65,75,85,95};
    int n = 95;
    binarySearch(arr,n);
    
    return 0;
}
Caspex
  • 3
  • 2
  • 3
    If you want help improving working code, you should post this on [CodeReview.SE](https://codereview.stackexchange.com/help/how-to-ask). If you do decide to do so, please delete the question here. – NathanOliver Apr 18 '22 at 13:20
  • What do you hope to gain by not using the standard implementation? You’ve now written code you have to maintain and debug. When your data increases in size to an array of 11 because you made a mistake, you now have to rewrite it. You’re spending all your time on the binary search instead of what it was you actually wanted to write. If passing the upper and lower bounds bothers you that much, you can always write a wrapper function that takes a generic container by reference and calls the actual std binary search with the proper arguments. Win-win. – Taekahn Apr 18 '22 at 13:31
  • You’re calculating your `mid` wrong btw – Taekahn Apr 18 '22 at 13:35
  • @Taekahn I didn't mention this in my original post since I wanted to keep the details that don't matter off the post. But this was actually a question from my school question paper. And how am I calculating my mid wrong? Doesn't the code work? – Caspex Apr 18 '22 at 13:37
  • The mid should be calculated as `(X + Y)/2` Its a common mistake to do subtraction, and it sometimes works. – Taekahn Apr 18 '22 at 13:41
  • 1
    @Taekahn even `(X + Y)/2` is flawed as it can overflow. IIRC, `mid = low + ((high - low) / 2)` is what you really want. – NathanOliver Apr 18 '22 at 13:45

0 Answers0