二分查找

#include <iostream>
#include <algorithm>
using namespace std;

bool binarySearch(int a[],int x,int n)
{
    int left = 0,right = n-1;
    while(left <= right)
    {
        int mid = (left + right) / 2;
        if(x == a[mid]) return true;
        if(x < a[mid])   right = mid -1;
        else left = mid +1;
    }
    return false;
}

int main()
{
    int a[1000];
    int n,m;
    cout << "请输入数组的个数和要查找的数:" <<endl;
    while(cin >> n >> m)
    {
        for(int i = 0; i < n; i++)
        {
            cin >> a[i];
        }
        sort(a,a+n);
        bool flag;
        flag = binarySearch(a,m,n);
        if(flag)
        {
            cout << "Found!" << endl;
        }
        else
        {
            cout << "Not found!" <<endl;
        }
    }
    return 0;
}

 

你可能感兴趣的:(二分查找)