DreamWorks

Never say Never。
  博客园  :: 首页  :: 新随笔  :: 联系 :: 订阅 订阅  :: 管理

折半查找

Posted on 2013-07-23 18:20  _Babyface  阅读(107)  评论(0编辑  收藏  举报
//折半查找的递归算法
int Search_rec(int r[],int low,int high,int key)
{
    int mid;
    while (low<=high)
    {
        mid = (low+high)/2;
        if (key<r[mid])
            return Search_rec(r,low,mid-1,key);
        else if(key>r[mid])
            return Search_rec(r,mid+1,high,key);
        else
            return mid;
    }
    return -1;
}
//折半查找算法
int Search_rec1(int r[],int low,int high,int key)
{
    int mid;
    while (low<=high)
    {
        mid = (low+high)/2;
        if (key == r[mid])
            return mid;
        else if (key<r[mid])
            high = mid-1;
        else
            low = mid +1;
    }
    return -1;
}
View Code