ITPub博客

首页 > 应用开发 > IT综合 > 【C++】二分查找与递归

【C++】二分查找与递归

原创 IT综合 作者:风尘_NULL 时间:2017-07-26 09:54:20 0 删除 编辑
#include
//#include 
//#include 
//#include 
#include 
using std::string;
#include 
#include 
#include 
#include 
using std::vector;
bool search_value(std::vector <int>::const_iterator* start,std::vector <int>::const_iterator* end,std::vector <int> ::size_type size,const int search_values,std::vector <int>::const_iterator* &results);

bool search_value(std::vector <int>::const_iterator* start,std::vector <int>::const_iterator* end,std::vector <int> ::size_type size,const int search_values,std::vector <int>::const_iterator* &results){

 std::vector <int>::const_iterator mid=(*start)+int(ceil(size/2))-1;
 //return true;
 //std::cout<<*mid<<std::endl;</std::endl;<>

 if(*mid==search_values){

 results=∣
 return true;
 }


 if(*mid<search_values){
 int size=(*end)-mid+1;
 return search_value(&mid,end,size,search_values,results);
 }
 if(*mid>search_values){
 int size=mid-(*start)+1;
 return search_value(start,&mid,size,search_values,results);
 }
 return false;
}
int main()
{
 //指针千万注意初始化,否则有崩溃的风险
 std::vector <int>::const_iterator* tts = NULL;
 bool rest;
 //查找元素在容器中的位置
 std::vector <int>::difference_type position;
 vector <int> ivec={1,2,3,4,18,23,85,22};

 vector <int>::const_iterator start=ivec.begin();
 vector<int>::const_iterator end=ivec.end();
 int aa=23;
 int size=ivec.size();
 rest=search_value(&start,&end,size,aa,tts);
 if(NULL == tts) {
 std::cout << "tts is NULL." << std::endl;
 }
 if(rest){

 position=*tts-start+1;
 std::cout<<"the position in container is:"<<position<<",the value of the search is:"<<*(*tts)<<std::endl;</position<<
 }else{
 std::cout<<"no values match"<<std::endl;
 }
}

结果如下:

</search_values){<>

来自 “ ITPUB博客 ” ,链接:https://blog.itpub.net/30221425/viewspace-2142570/ ,如需转载,请注明出处,否则将追究法律责任。

请登录后发表评论 登录
全部评论
腾讯科技(深圳)有限公司 DBA

注册时间:2015-04-24

  • 博文量
    76
  • 访问量
    238232