递归-----二分法查找

递归是一个看起来简单的概念:所有调用自己的例程都是递归。尽管看起来很简单,但是理解起来并且应用递归可能相当复杂。本次博主写的内容是关于二分法查找的内容。我记得我之前写过一个二叉树的遍历就是利用递归的。气势二分法和二叉树很相似,所以如果需要查找,大家也是可是可以选择递归去做。
问题描述;
实现一个函数,在一个已经排序的整形数组中进行二分搜索,找到给定的数据的小标。讨论效率,并与其它的搜索进行比较。
首先,大家要明白在数组遍历查找的算法复杂度是:0(n),而且没有利用到数组有序的性质。这个时候大家就要明白,对于有序的东西,二分法十分有效,可以利用有序性快速的查找。对于二分法的时间复杂度,大家都应该明白是log(n).所以如果要在数组中查找一个数据,如果直接遍历是:0(n),如果先排序再二分法查找:O(nlog(n))+O(log)。所以说,一般情况下也是先排序再二分查找更有时间有效性。当然这都是不考虑空间复杂度的情况下。
好了,下面就随便写了写二分法查找的模板。
// 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<<"position is "<<pos-source+1<<endl;
else cout<<"the target is not exist."<<endl;
pos=binary_search(source,length,2);
if(pos) cout<<"position is "<<pos-source+1<<endl;
else cout<<"the target is not exist."<<endl;
pos=binary_search(source,length,3);
if(pos) cout<<"position is "<<pos-source+1<<endl;
else cout<<"the target is not exist."<<endl;
pos=binary_search(source,length,4);
if(pos) cout<<"position is "<<pos-source+1<<endl;
else cout<<"the target is not exist."<<endl;
pos=binary_search(source,length,5);
if(pos) cout<<"position is "<<pos-source+1<<endl;
else cout<<"the target is not exist."<<endl;
pos=binary_search(source,length,6);
if(pos) cout<<"position is "<<pos-source+1<<endl;
else cout<<"the target is not exist."<<endl;
pos=binary_search(source,length,7);
if(pos) cout<<"position is "<<pos-source+1<<endl;
else cout<<"the target is not exist."<<endl;
    pos=binary_search(source,length,8);
if(pos) cout<<"position is "<<pos-source+1<<endl;
else cout<<"the target is not exist."<<endl;
pos=binary_search(source,length,12);
if(pos) cout<<"position is "<<pos-source+1<<endl;
else cout<<"the target is not exist."<<endl;
return 0;
}
运行结果:
递归-----二分法查找



评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值