// binarysearch.h template <typename T> int binarysearch(T val, T data[], int begin, int end, bool flag) { if(flag){ // data 为升序数组 if(val< data[begin] || val > data[end]){ return -1; } int medidx = (begin+end)/2; if(val == data[medidx]){ return medidx; }else if(val > data[medidx]){ binarysearch(val, data, medidx + 1, end, flag); }else{ binarysearch(val, data, begin, medidx - 1, flag); } }else{ // data为降序数组 if(val > data[begin] || val < data[end]){ return -1; } int medidx = (begin+end)/2; if(val == data[medidx]){ return medidx; }else if(val > data[medidx]){ binarysearch(val, data, begin, medidx - 1, flag); }else{ binarysearch(val, data, medidx + 1, end, flag); } } cout << "Error input, check up and run again!\n"; return -1; }
test.cpp
#include <iostream> #include <iomanip> #include <limits> using std::cout; using std::endl; #include "binarysearch.h" int main() { //int data[] = {1, 2, 5, 7, 14, 15, 18, 21, 24, 27, 28, 33, 39, 41, 57, 66}; //int sz = sizeof(data)/sizeof(data[0]); //int val = 77; //int idx = binarysearch(val ,data, 0, sz-1); //if(idx != -1){ // cout << "find " << val << " at index " << idx << endl; //}else{ // cout << val << " not found!\n"; //} int data2[] = {100, 97, 92,89,87,86,85,81,74,72,70,63,61,55,48,47,41,30,23,17,15,7}; int sz2 = sizeof(data2)/sizeof(data2[0]); int val2 = 100; int idx2 = binarysearch(val2, data2, 0, sz2 -1 , false); if(idx2 != -1){ cout << "find " << val2 << " at index " << idx2 << endl; }else{ cout << val2 << " not found!\n"; } return 0; }