//Binary search using c++. The main function does not give any output. This is simple binary search algorithm implementation.
#include <iostream>
using namespace std;
int BinarySearch(int *a, int x, int n ){
int left = 0;
int right = n-1;
while(left<=right){
int middle = left + right /2;
if (x>a[middle]) {
left = middle +1;
}
else if (x<a[middle]){
right = middle -1;
}
else return middle;
}
return 1;
}
int main(int argc, const char * argv[])
{
cout<<"Hello World";
int a[] ={1,2,3,4,5,6,7,8,9,10};
int x = 3;
int n = 10;
int var = BinarySearch(a, x, n);
cout<<"The search result:"<<endl;
cout<< var;
return 0;
}
You are missing paranthesis around
int middle = left + right / 2;
It must be
int middle = (left + right) / 2;
And you might also want to return
return a[middle]; //instead of middle;
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.