二分查找/折半查找(C++实现)

要求:给定已 按升序排好序的n个元素a[0:n-1],现要在这n个元素中找出一特定元素x。
 
分析:
  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一样,只不过是查找的规模缩小了。这就说明此问题满足分治法的第二个和第三个适用条件。
 
 非递归算法描述:
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++代码:
#include<iostream>
#define MAX_SIZE 102
using namespace std;
template<class Type>
int BinarySearch(Type a[],const Type& x,int n)
{
    int left=0;
    int right=n-1;
    while(left<=right)
    {
        int middle=(left+right)/2;
        if(a[middle]==x)
            return middle;
        if(x>=a[middle])
            left=middle+1;
        else
            right=middle-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<<"该数不存在!"<<endl;
    else
    cout<<p+1<<endl;
    return 0;
}

 

递归算法描述:

If  low >high  then  return 0
 else
    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
 
递归算法C++代码:
#include<iostream>
#define MAX_SIZE 102
using namespace std;
template <class T>
int BinarySearch(T a[],const T&x,int n,int left,int right)
{
    if(left>=right)
        return -1;
    else
    {
        if(a[(left+right)/2]==x)
            return (left+right)/2;
        else if(x>=(left+right)/2)
            return BinarySearch(a,x,n,(left+right)/2+1,right);
        else if(x<(left+right)/2)
            return BinarySearch(a,x,n,left,(left+right)/2-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,0,len-1);
    if(p==-1)
        cout<<"该数不存在!"<<endl;
    else
    cout<<p+1<<endl;
    return 0;
}

 

算法复杂度分析:
每执行一次算法的while循环, 待搜索数组的大小减少1/2。
因此,在最坏情况下,while循环被执行了O(logn) 次。
循环体内运算需要O(1) 时间,因此整个算法在最坏情况下的计算时间复杂性为 O(logn) 

转载于:https://www.cnblogs.com/auto1945837845/p/5384316.html

  • 0
    点赞
  • 2
    收藏
    觉得还不错? 一键收藏
  • 0
    评论

“相关推荐”对你有帮助么?

  • 非常没帮助
  • 没帮助
  • 一般
  • 有帮助
  • 非常有帮助
提交
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值