这个是改良版的二分查找树,是通过阅读nebula device意外获得,这边先记下来。。
typedef vector<int> IntVec;
16 int binarysearch(const IntVec& vec, int element)
17 {
18 int num = vec.size();
19 int begin = 0;
20 int end = num - 1;
21 int half;
22 int mid;
23 int count = 0;
24 printf("binarysearch--- vec count=%d, element=%d\n",num, element);
25 while(begin <= end)
26 {
27 count++;
28 if((half = num / 2))
29 {
30 if (element == vec[begin])
31 {
32 printf("count=%d\n", count);
33 return begin;
34 }
35 if (element == vec[end])
36 {
37 printf("count=%d\n", count);
38 return end;
39 }
40 mid = begin + ((num & 1)? half : (half - 1));
41 printf("vec[%d]=%d\n",mid, vec[mid]);
42
43 if(element < vec[mid])
44 {
45 end = mid - 1;
46 num = (num & 1)? half: half - 1;
47 printf("element < vec[mid]-- end, num\n", end, num);
48 }
49 else if (element > vec[mid])
50 {
51 begin = mid + 1;
52 num = half;
53 printf("element < vec[mid]-- end, num\n",end, num);
54 }
55 else
56 {
57 printf("count=%d\n", count);
58 return mid;
59 }
60 }
61 else if(num)
62 {
63 if (element != vec[begin])
64 {
65 return -1;
66 }
67 else
68 {
69 return begin;
70 }
71 }
72 else
73 {
74 break;
75 }
76 }
77 return -1;
78 }