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;
}