首页 > 代码库 > 二分查找法的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;}
声明:以上内容来自用户投稿及互联网公开渠道收集整理发布,本网站不拥有所有权,未作人工编辑处理,也不承担相关法律责任,若内容有误或涉及侵权可进行投诉: 投诉/举报 工作人员会在5个工作日内联系你,一经查实,本站将立刻删除涉嫌侵权内容。