首页 > 代码库 > 二分查找法的C++泛型实现

二分查找法的C++泛型实现

算法很简单,直接贴代码啦

 

#include <iostream>using namespace std;template<typename T>int binary_search(const T s[],const int size,const T &m){ if(size <= 0){  return -1; } int i = size/2; int k = 1; int step = 1; while(step > 0 && i >= 0 && i < size){  step = size/(2*++k);  if(m == s[i]){   return i;  }else if(m > s[i]){   i += step;  }else{   i -= step;  } } return -1;}int main(){ long s[]={1,3,5,6,19,27,38,45,687,6789,10000};  int len = sizeof(s)/sizeof(long); cout<<"0:"<<binary_search<long>(s,len,1)<<endl; cout<<"1:"<<binary_search<long>(s,len,3)<<endl; cout<<"5:"<<binary_search<long>(s,len,27)<<endl; cout<<"10:"<<binary_search<long>(s,len,10000)<<endl; cout<<"-1:"<<binary_search<long>(s,len,10001)<<endl; cout<<"-1:"<<binary_search<long>(s,len,44)<<endl; cout<<"-1:"<<binary_search<long>(s,len,0)<<endl; return 0;}