二分查找法

不断分段找中点,判断中点是否是要寻找的num

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
// 获取 num 在 vector 中的 index
int findIndex(const vector<int>& vector, int num);

int main(int argc, char *argv[])
{
vector<int> v;
for(int i=0; i<9; i++)
{
v.emplace_back();
auto& num = v.back();
num = i*2;
cout << " v.back: "<< v.back();
}
int id = findIndex(v, 6) ;
if(id < 0 )
cout << "no such number !" <<endl;
else
cout << "index of number is : "<< id <<endl;
return 0;
}

int findIndex(const vector<int>& vector, int num)
{
Q_ASSERT(vector.size() >0 );
int size = vector.size();
if(vector.at(0) ==num ) return 0;
if(size==1 && vector.at(0) !=num ) return -1;
if(num == vector.back() ) return size-1;

int begin, mid, end;
begin =0; end = vector.size()-1;
mid = (begin + end) / 2;
int count = 0;
while(num != vector.at(mid) )
{
count++;
if(count > log2(size) )
{
return -1;
break;
}
// 比较mid和num, 按情况只取一段进行递归比较,这样才降低复杂度
if( num > vector.at(mid) )
{
begin = mid; end = end;
mid = (begin + end) / 2;
}
else
{
begin = begin; end = mid;
mid = (begin + end) / 2;
}
}
return mid;
}