折半(对半)搜索算法

二分搜索算法要求有序表采用顺序存储,其中折半搜索(又称折半搜索)是二分搜索的一个特例,设当前搜索的子表为(Aleft,Aleft+1,Aleft+2,……,Aright),令

m=(left+right)/ 2。这种二分搜索被称为对半搜索。对半搜索算法将表划分成几乎相等大小的两个字表。

下面给出对半搜索的递归算法(使用模板,具体应用时可以再进行相应修改):

template<class T>
int SortableList<T>::Bsearch(const T &x,int left,int right)
{
    if(left<=right)       //若表(子表)非空
    {
        int m=(left+right)/2;   //对半分割
        if(x<l[m]) return Bsearch(x,left,m-1);  //搜索左子树
        else if(x>l[m]) return Bsearch(x,m+1,right);  //搜索右子树
        else
            return m;  //搜索成功
    }
    return -1;     //搜索失败
}

递归函数的效率往往较低,常希望得到相应的迭代算法,下面给吃对半搜索的迭代算法:

template<class T>
int SortableList<T>::Bsearch(const T &x) const
{
   int m,left=0,right=n-1;
   while(left<=right){
       m=(left+right)/2;
       if(x<l[m])  right=m-1;
       else if(x>l[m])  left=m+1;
       else    return m;  //搜索成功
    }
    return -1;     //搜索失败
}

版权声明:本文为博主原创文章,未经博主允许不得转载。

原文地址:https://www.cnblogs.com/Tobyuyu/p/4965575.html