二分查找/折半查找(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