二分查找

#include <stdio.h>
#include <stdlib.h>
#define SIZE 100000
//BinarySearch
int BinarySearch(int b[],int low,int high,int searchKey)
{
    int middle;
    while(low<=high)
    {
        middle=(low+high)/2;
        if(b[middle]==searchKey)
            return middle;
        else if(b[middle]>searchKey)
            high=middle-1;
        else
            low=middle+1;
    }
    return -1;
};

int main()
{
    int a[SIZE];
    int i;
    for(i=0;i<=SIZE-1;i++)
        a[i]=2*i;
    int key;
    printf("Please enter a key:\n");
    scanf("%d",&key);
    int c=BinarySearch(a,0,SIZE-1,key);
    if(c!=-1)
        printf("the key is %d",c);
    else
        printf("can't find this number!");
    return 0;
}

 

posted @ 2013-03-08 10:51  天晴会下雨  阅读(129)  评论(0编辑  收藏  举报