码迷,mamicode.com
首页 > 编程语言 > 详细

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

时间:2014-08-05 15:56:49      阅读:348      评论:0      收藏:0      [点我收藏+]

标签:二分查找   泛型   算法   

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

 

#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;
}


 

二分查找法的C++泛型实现,布布扣,bubuko.com

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

标签:二分查找   泛型   算法   

原文地址:http://blog.csdn.net/qq910894904/article/details/38385103

(0)
(0)
   
举报
评论 一句话评论(0
登录后才能评论!
© 2014 mamicode.com 版权所有  联系我们:gaon5@hotmail.com
迷上了代码!