// blog_recursive_binary_search.cpp : 定义控制台应用程序的入口点。
//
#include "stdafx.h"
#include
#include
using namespace std;
template
void _binary_search(T *head,T *tail, T target, T
**exist_pos)//这里为什么要用地址的指针?因为我们想要修改的地址本身,而不是地址指向的内容,所以这里希望大家注意
{
if(*head>target||*tail
else if(*head==target){*exist_pos=head;return ;}//首位判断
else if(*tail==target){*exist_pos=head;return;}//尾部判断
else
if(head==tail-1)return;//r如果首尾都不是,而且首尾相邻,那么直接返回,找不到target
else
{
size_t mid_pos=(tail-head)/2;//找到中间偏移位置
if(*(head+mid_pos)==target)
{*exist_pos=head+mid_pos;return; }//查看中间数据是不是,如果是直接返回
else if(*(head+mid_pos)>target)
_binary_search((head),(head+mid_pos),target,exist_pos);//中间数据不是的话,就要判断大小,找到下一个应该递归的区间
else
_binary_search((head+mid_pos),tail,target,exist_pos);
}
}
template
T* binary_search(T *source,const size_t length, T
target)
{
T* exist_pos=nullptr;//这个指针中存储了target的位置
_binary_search(source,source+length-1,target,&exist_pos);
return exist_pos;
}
int main()
{
int source[10]={1,2,3,4,5,6,7,8,9,10};
const size_t length=10;
int *pos=nullptr;
pos=binary_search(source,length,1);
if(pos) cout<
"<
else cout<
pos=binary_search(source,length,2);
if(pos) cout<
"<
else cout<
pos=binary_search(source,length,3);
if(pos) cout<
"<
else cout<
pos=binary_search(source,length,4);
if(pos) cout<
"<
else cout<
pos=binary_search(source,length,5);
if(pos) cout<
"<
else cout<
pos=binary_search(source,length,6);
if(pos) cout<
"<
else cout<
pos=binary_search(source,length,7);
if(pos) cout<
"<
else cout<
pos=binary_search(source,length,8);
if(pos) cout<
"<
else cout<
pos=binary_search(source,length,12);
if(pos) cout<
"<
else cout<
return 0;
}
运行结果: