码迷,mamicode.com
首页 > 其他好文 > 详细

二分查找的递归与非递归算法

时间:2014-06-25 13:51:56      阅读:174      评论:0      收藏:0      [点我收藏+]

标签:class   blog   ext   os   算法   name   

/*
二分查找的递归与非递归算法
*/
#include <iostream>
#include <cstdio>
using namespace std;

bool bisrch( int low,int high,int v,int *text ) //递归写法
{
    int i,mid;
    mid=( low+high )/2;
    if( low>high ) return false;
    if( v==text[mid] )  return true;
    else if( v<text[mid] )  return bisrch( low,mid-1,v,text );
    else return bisrch( mid+1,high,v,text );
}

bool bisrch1( int low,int high,int v,int *text ) //非递归写法
{
    int i,mid;
    while( low<=high )
    {
        mid=(low+high)/2;
        if( text[mid]==v )  return true;
        else if( v<text[mid] ) high=mid-1;
        else low=mid+1;
    }
    return false;
}

int main()
{
    int text[10];
    int i;
    for( i=0;i<10;i++ )
        text[i]=i;
    cout<<"递归写法:"<<endl;
    for( i=0;i<20;i++ )
    {
        if( bisrch(0,9,i,text) ) cout<<"FOUND!"<<endl;
        else cout<<"NOT FOUND!"<<endl;
    }
    cout<<"非递归写法:"<<endl;
    for( i=0;i<20;i++ )
    {
        if( bisrch1(0,9,i,text) ) cout<<"FOUND!"<<endl;
        else cout<<"NOT FOUND!"<<endl;
    }
    return 0;
}

  

二分查找的递归与非递归算法,布布扣,bubuko.com

二分查找的递归与非递归算法

标签:class   blog   ext   os   算法   name   

原文地址:http://www.cnblogs.com/ccguo/p/3806698.html

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