1: /*
2: author:justinzhang
3: email:uestczhangchao@gmail.com
4: time:2012-8-30 18:54:01
5: desc: binary search from the aocp p380
6: */
7:
8: #include <iostream>
9: #include <vector>
10: #include <memory> //for auto_ptr, but auto_ptr does not support arrays
11: #include <ctime> // for time(0) function
12: #include <cstdlib> // for srand and rand function
13: #include <algorithm> // for sort and binary_search function
14: using namespace std;
15:
16: template <class type>
17: type random(type start, type end)
18: {
19: srand((int)time(0)*rand());
20: return (start + (end-start)*rand()/(RAND_MAX+1.0));
21: }
22:
23: template<class type> bool my_binary_search(vector<type> data, int begin, int end, type value)
24: {
25: int L = begin;
26: int U = end;
27: while(U>L) //注意此处不要写成了U>=L,如果是>=,并且数组下标从0开始的话,就会导致vector下标越界
28: {
29: int M = L+(U-L)/2;
30: if(data[M] > value)
31: U = M-1;
32: else if(data[M] < value)
33: L = M+1;
34: else
35: return true;
36: }
37: return false;
38: }
39:
40: template <class type> bool recursive_binary_search(vector<type> data, int begin, int end, type key)
41: {
42: if(begin >= end)
43: return false;
44: else
45: {
46: int mid = begin+(end - begin)/2;
47: if(data[mid] > key)
48: recursive_binary_search(data,begin,mid-1,key);
49: else if(data[mid] < key)
50: recursive_binary_search(data,mid+1,end,key);
51: else
52: return true;
53: }
54: }
55:
56:
57: int main()
58: {
59: /*auto_ptr does not support for arrays, C11 support*/
60: //auto_ptr<double> auto_ptr_data(new double);
61: //*auto_ptr_data = 100;
62: //cout << *auto_ptr_data << endl;
63:
64: vector<double> data;
65: for(unsigned int i=0; i<20; i++)
66: {
67: data.push_back(random<double>(1,10));
68: }
69:
70: data.push_back(77.77);
71:
72: vector<double> copy_data(data.size());
73: copy(data.begin(),data.end(),copy_data.begin());
74:
75: for(unsigned int i=0; i<10; i++)
76: {
77: cout << data[i] << "==" << copy_data[i] << endl;
78: }
79:
80: sort(data.begin(),data.end());
81: for(unsigned int i=0; i<data.size(); i++)
82: if(binary_search(data.begin(),data.end(),copy_data[i]))
83: {
84: cout << "found item: " << copy_data[i] << endl;
85: }
86:
87: /*-----test non-recursive version-----*/
88: if(my_binary_search<double>(data,0,data.size(),898))
89: {
90: cout << " find item: " << 898<< endl;
91: }
92: else
93: cout << "not found item:" << 898 << endl;
94:
95: /*----test recursive binary search-----*/
96: vector<double> A(10,random(1,10)); //初始化向量A,每一个元素都为1
97: for(int i=0; i<10; i++)
98: cout << A[i] << endl;
99: if(recursive_binary_search<double>(A,1,5,1))
100: cout << "found !" << endl;
101:
102:
103: return 0;
104: }