C语言笔试题(4)——二分法查找

#include 

int bfind(int *a, int len, int num)
{
    int min = 0;
    int max = len - 1;
    int mid;

    while(min <= max)
    {
        mid = (min + max) / 2;
        
        if (a[mid] > num)
            max = mid - 1;
        else if (a[mid] < num)
            min = mid + 1;
        else
            return mid;
    }

    return -1;
}

int main(int argc, const char *argv[])
{
    int array[10] = {1, 5, 34, 56, 67, 68, 253, 342, 346, 2666};
    int i;

    //for (i = 0; i < 10; i++)
       // array[i] = i + 1 ;

    printf("dst: %d\n",bfind(array, 10, 1));

    return 0;
}


你可能感兴趣的:(C/C++笔试题)