1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26 27 28 29 30
|
#include <iostream>
#include <string>
#include <vector>
using namespace std;
int binary_search(const vector<int>& v, int x, int begin, int end){
if(begin >= end){ return -1;}
else {
int mid = (begin + end) / 2;
if (x == v[mid]){ return mid;}
else if(x < v[mid]){ return binary_search(v, x, begin, mid);}
else if(x > v[mid]){ return binary_search(v, x, mid + 1, end);}
}
return 1000;
}
int binary_search(const vector<int>& v, int x){
return binary_search(v, x, 0, v.size());
}
int main(){
vector<int> v = {80, 68, 50, 45, 30, 20, 10};
int target = 50;
if (binary_search(v, target, 0, v.size()) == -1){
cout << "Range is empty! -1 returned!" << endl;
}
else{
cout << "Inde ox binary_search() is: " << binary_search(v, target, 0, v.size()) << endl;
}
}
|