注:区间是左闭右开的
普通二分查找
typedef int DataType; int binary_search_any( DataType datas[], int begin, int end, DataType o) { int midindex(0); while (begin < end) { midindex = (begin + end) >> 1; if (datas[midindex] < o) begin = midindex + 1; else if (datas[midindex] > o) end = midindex; else return midindex; } return -1; }
查找最左边的元素——难点主要在于中间元素的处理上
int binary_search_first( DataType datas[], int begin, int end, DataType o) { int midindex(0); while (begin < end) { midindex = (begin + end - 1) >> 1; if (datas[midindex] < o) begin = midindex +1; else if (datas[midindex] > o) end = midindex; else if ((datas[midindex] == o) && (begin + 1 == end)) return midindex; else end = midindex + 1; } return -1; }
查找最右边的元素
int binary_search_last( DataType datas[], int begin, int end, DataType o) { int midindex(0); while (begin < end) { midindex = (begin + end) >> 1; if (datas[midindex] < o) begin = midindex + 1; else if (datas[midindex] > o) end = midindex; else if ((datas[midindex] == o) && (begin + 1 == end)) return midindex; else begin = midindex; } return -1; }
测试
1 #include <iostream> 2 #include <map> 3 #include <string> 4 5 using namespace std; 6 7 8 typedef int (*BS)( DataType [], int , int , DataType ); 9 10 map<string, BS> sfs; 11 12 void test( DataType datas[], int begin, int end, DataType o) 13 { 14 cout << "#####################################################" << endl; 15 for(map<string, BS>::iterator iter = sfs.begin(); iter != sfs.end(); ++ iter) 16 { 17 cout 18 << iter->first 19 << "\t" 20 << o 21 << "\t" 22 << ( * iter->second)(datas, begin, end, o) 23 << endl; 24 } 25 } 26 27 int main() 28 { 29 DataType dts[] = {0,0,0,1,1,1,2,2,2}; 30 sfs.insert(pair<string, BS>("binary_search_any", &binary_search_any)); 31 sfs.insert(pair<string, BS>("binary_search_first", &binary_search_first)); 32 sfs.insert(pair<string, BS>("binary_search_last", &binary_search_last)); 33 test(dts, 0, 9, 0); 34 test(dts, 0, 9, 1); 35 test(dts, 0, 9, 2); 36 test(dts, 0, 9, 3); 37 test(dts, 0, 9, 10); 38 test(dts, 0, 9, -1); 39 return 0; 40 }