数据结构-二分查找

 1 #include <iostream>
 2 #include <algorithm>
 3 #include <vector>
 4 #include "example_vec.h"
 5 #include "printCollection.h"
 6 using namespace std;
 7 
 8 extern vector<int> example_vec;
 9 
10 template<typename comparable>
11 int binarySearch(const vector<comparable> &a, const comparable &x){
12     int low = 0, high = a.size() - 1;
13 
14     while(low <= high)
15     {
16         int center = (high + low)/2;
17         if(x < a[center])
18             high = center - 1;
19         else if(x > a[center])
20             low = center + 1;
21         else
22             return center;
23     }
24 
25     return -1;
26 }
27 int main(){
28 
29     cout << "The count of array is: " << example_vec.size() << endl;
30 
31     printCollection(example_vec);
32 
33     stable_sort(example_vec.begin(), example_vec.end());
34 
35     printCollection(example_vec);
36 
37     cout << "The index of 13 is " << binarySearch(example_vec, 13) << endl;
38 
39     return 0;
40 
41 }

 

posted on 2014-07-05 15:39  醉清风JM  阅读(244)  评论(0编辑  收藏  举报

导航