二分查找(循环法+递归法)

1.要求:

给定已按升序排好序的n个元素a[0:n-1],现要在这n个元素中找出一特定元素x。

2.分析:

  1. 该问题的规模缩小到一定的程度就可以容易地解决;

    如果n=1即只有一个元素,则只要比较这个元素和x就可以确定x是否在表中。因此这个问题满足分治法的第一个适用条件

  2. 该问题可以分解为若干个规模较小的相同问题;
  3. 分解出的子问题的解可以合并为原问题的解;
  4. 分解出的各个子问题是相互独立的。

比较x和a的中间元素a[mid]

若x=a[mid],则x在L中的位置就是mid;

如果x<a[mid],则x在a[mid]的前面;

如果x>a[mid],则x在a[mid]的后面。

无论在哪部分查找x,其方法都和在a中查找x一样,只不过是查找的规模缩小了。这就说明此问题满足分治法的第二个和第三个适用条件。

3.循环算法

循环算法描述:

binarysearch
low ←1;high ←n;j ←0

while (low≤high) and (j=0)
    mid ←(low+high)/2
    if  x=A[mid] then  j ←mid
    else if  x<A[mid] then high ←mid-1
    else low ←mid+1
end  while

return  j

循环算法C++代码:

//循环法二分查找
template<class Type>
int BinarySearch(Type a[], const Type& x, int n){
    //a为数组,x为待查值,n为数组元素个数
    //TODO检查输入
    int low = 0;
    int high = n-1;
    while(low <= high){
        int mid = (low + high) / 2;
        if (a[mid] == x)
            return mid;
        else if(a[mid] < x)
            low = mid + 1;
        else
            high = mid - 1;
    }
    return -1;
}

int main(){
    int a[MAX_SIZE];
    //输入
    int i, len, x, p;
    cin>>len;
    for(i=0; i<len; i++){
        cin>>a[i];
    }
    cin>>x;

    p = BinarySearch(a, x, len);
    if(p == -1)
        cout<<false;
    else
        cout<<p<<endl;

    return 0;
}

4.递归算法

递归算法描述:

if  low >high  then  return -1
mid ←(low+high)/2

if  x=A[mid] then return mid
else if x<A[mid] then return binarysearch(low,mid-1)
else return  binarysearch(mid+1,high)
end  if

递归算法代码:

//递归法二分查找
template<class T>
int BinarySearch(T a[], const T& x, int low, int high){
    //TODO检查输入
    if(low > high)
        return -1;
    int mid = (low + high) / 2;

    if(a[mid] == x)
        return mid;
    else if(a[mid] < x)
        return BinarySearch(a, x, mid+1, high);
    else
        return BinarySearch(a, x, low, mid-1);
}


int main(){
    int a[MAX_SIZE];
    //输入
    int i, len, x, p;
    cin>>len;
    for(i=0; i<len; i++){
        cin>>a[i];
    }
    cin>>x;

    int p1 = BinarySearch(a, x, 0, len-1);
    if(p1 == -1)
        cout<<false;
    else
        cout<<p1<<endl;

    return 0;
}

算法复杂度分析:

每执行一次算法的while循环, 待搜索数组的大小减少1/2。

因此,在最坏情况下,while循环被执行了O(logn) 次。

循环体内运算需要O(1) 时间,因此整个算法在最坏情况下的计算时间复杂性为O(logn) 

参考:

1.二分查找/折半查找(C++实现):https://www.cnblogs.com/auto1945837845/p/5384316.html

2.c++二分查找实现(非递归和递归方式):https://blog.csdn.net/richerg85/article/details/19020965

评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值