-
Notifications
You must be signed in to change notification settings - Fork 0
Expand file tree
/
Copy pathbinary_search.cpp
More file actions
75 lines (66 loc) · 1.46 KB
/
binary_search.cpp
File metadata and controls
75 lines (66 loc) · 1.46 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
68
69
70
71
72
73
74
75
#include<iostream>
#include<algorithm>
#include<vector>
using namespace std;
void input_data(vector<int> & data)
{
cout<<"input data";
int tmp;
while(cin >> tmp && tmp != -10000){
data.push_back(tmp);
}
}
void output_data(vector<int> & data)
{
cout << "输入的数据:";
for(vector<int>::iterator it = data.begin(); it != data.end(); it++)
{
cout << *it << '\t';
}
cout << endl;
}
int bin_search(vector<int> & data, int val)
{
int low = 0, high = data.size() - 1;
int mid;
while(low <= high){
mid = (low + high) / 2;
if(data[mid] < val)
low = mid + 1;
else if(data[mid] > val)
high = mid - 1;
else
return mid;
}
return data.size();
}
int binary_search(vector<int> &v, int first, int last, int value)
{
int half = (first + last)/2;
if(v[half] == value)
return half;
else if(v[half] < value)
return binary_search(v,half,last,value);
else
return binary_search(v,first,half,value);
}
int main()
{
vector<int> data;
srand(unsigned(time(0)));
for(int i = 0; i < 10; ++i)
data.push_back(rand() % 10);
sort(data.begin(), data.end());
cout << "data:" << endl;
for(int i =0; i < 10; ++i)
cout << data[i] << " ";
cout << endl;
int val = data[rand()%10];
int index = binary_search(data,0,data.size()-1,val);
if(index == data.size()){
cout << "index = " << index << ", data doesnot have" << val << endl;
return 0;
}
cout << "index = " << index << "data[index]=" << data[index] << endl;
return 0;
}