二分法递归查找c语言4参数,递归-----二分法查找

// 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;

}

运行结果:

a4c26d1e5885305701be709a3d33442f.png

评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值