-
Notifications
You must be signed in to change notification settings - Fork 0
Expand file tree
/
Copy pathbinary_search.cpp
More file actions
67 lines (64 loc) · 1.38 KB
/
binary_search.cpp
File metadata and controls
67 lines (64 loc) · 1.38 KB
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
66
67
#include <iostream>
#include <cstdio>
#include <cstring>
#include <string>
#include <algorithm>
#include <cmath>
#include <sstream>
#include <set>
#include <map>
#include <queue>
#include <stack>
using namespace std;
bool binary_add(vector<int> data,int low,int high,int b)
{
long mid=(low+high)/2;
while(high>low)
{
mid=(low+high)/2;
if(b<=data[mid-1] && b>=data[mid]){
data.insert(data.begin()+mid,b);
return 1;
}
if(b<=data[mid] && b>=data[mid+1]){
data.insert(data.begin()+mid+1,b);
return 1;
}
if(data[mid]==b){
data.insert(data.begin()+mid,b);
return 1;
}
else if(data[mid]<b)
high=mid;
else
low=mid;
}
return 0;
}
int binary_search(vector<int> data,int low,int high,int b)
{
long mid=(low+high)/2;
if(data[low]==b)
return low;
else if(data[high]==b)
return high;
if(data[low]<b && data[high]>b)
while(high>low)
{
//cout<<low<<" "<<high<<" "<<data[low]<<" "<<data[high]<<endl;
mid=(low+high)/2;
if(data[mid]==b)
return mid;
else if(data[mid]>b)
high=mid;
else
low=mid;
}
return -1;
}
int main()
{
int A[]={1,2,3,4,5,6,7,8,9,10,11};
vector<int> as(A,A+11);
cout<<binary_search(as,0,4,4);
}