二分查找

#include<iostream>
#include<cstdio>
#include<cstring>
#include<stack>
#include<algorithm>
#define NOT_FOUND -1
using namespace std;
const int maxn=10007;
int n, k, a[maxn];

int Binary_Search()
{
    int left=1;
    int right=n;
    while(left <= right)
    {
        int mid=(left+right)/2;

        if(a[mid] > k)
            right=mid-1;
        else if(a[mid] < k)
            left=mid+1;
        else
            return mid;
    }
    return NOT_FOUND;
}
int main()
{
    while(~scanf("%d %d", &n, &k))
    {

        for(int i=1; i<=n; i++)
            scanf("%d", &a[i]);
         sort(a+1, a+n+1);
        if(Binary_Search()==-1)
            puts("查找失败!");
        else
            printf("输出查找到的下标:%d\n", Binary_Search());
    }
    return 0;
}

 

posted @ 2017-03-31 19:56  爱记录一切美好的微笑  阅读(104)  评论(0编辑  收藏  举报