-
Notifications
You must be signed in to change notification settings - Fork 0
/
Copy pathBinary search Basic.cpp
66 lines (57 loc) · 1.11 KB
/
Binary search Basic.cpp
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
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
#include <bits/stdc++.h>
using namespace std;
typedef long long ll;
#define MOD 1000000007
#define pb push_back
#define ppb pop_back
#define ff first
#define ss second
#define PI 3.141592653589793238462
#define set_bits __builtin_popcountll
#define all(x) (x).begin(), (x).end()
#define debug(x) cerr<<x<<" ";
//binary search simple
int solve(vector<int>&v,int target)
{
int l=0,h=v.size()-1;
while(l<=h)
{
int mid=l+(h-l)/2;
if(v[mid]==target)
{
return mid;
}
else if(v[mid]<target)
{
l=mid+1;
}
else
{
h=mid-1;
}
}
return -1;
}
int main()
{
ios_base::sync_with_stdio(false);
cin.tie(NULL);
clock_t time_req=clock();
//input of the vector
int n;
cin>>n;
vector<int>v;
while(n--)
{
int temp;
cin>>temp;
v.push_back(temp);
}
int target;
cin>>target;
int ans=solve(v,target);
cout<<ans;
#ifndef ONLINE_JUDGE
cout<<endl<<"Time: "<<fixed<<setprecision(6)<<((double)(clock()-time_req))/CLOCKS_PER_SEC<<endl;
#endif
}