Binary Seacrh Different Method
#include <bits/stdc++.h>
using namespace std;
int main(){
int n;
cin >> n;
vector<int> v;
for(int i=0;i<n;i++){
int x;cin >> x;
v.push_back(x);
}
int target;
cin >> target;
int l = 0;
int h = v.size()-1;
int mid;
while(h - l > 1){
mid = (h+l)/2;
if(v[mid] < target) l = mid + 1;
else h = mid;
}
if(target == v[l]) cout << l << "\n";
else if(target == v[h]) cout << h << "\n";
else cout << -1 << "\n";
}
Comments
Post a Comment