分治求二分法

时间:2021-03-06 04:04:29
#include <iostream>
using namespace std;
template <typename Type>
int BinarySearch(Type a[], const Type &x, int n)
{
    //在a[0]<=a[1]<=...<=a[n-1]中搜索x
    //找到x时返回其在数组中的位置,否则返回-1
    int left = 0;
    int right = n-1;
    while(left <= right)
    {
        int middle = (left+right)/2;
        if(x == a[middle])
        {
            return middle;
        }
        if(x > a[middle])
        {
            left = middle+1;
        } else {
            right = middle-1;
        }
    }
    //未找到x
    return -1;
}
int main()
{
    int n;
    cout<<"输入数组的大小n:"<<endl;
    cin>>n;
    int *a = new int[n];
    cout<<"输入数组中的数据:"<<endl;
    for(int i = 0; i < n; i++)
    {
        cin>>a[i];
    }
    int obj_num;
    cout<<"输入所要找的数:"<<endl;
    cin>>obj_num;
    int flag = BinarySearch(a,obj_num,n);
    if(-1 == flag)
    {
        cout<<"未找到obj_num"<<endl;
    } else {
        cout<<"找到obj_num,其在数组中的下标为:"<<flag<<endl<<"是第"<<flag+1<<"个数"<<endl;
    }
    delete a;
    return 0;
}