#include <stdio.h>
#include <stdlib.h>
int fun(int *a, int n, int k)
{
int low = 0, high = n - 1;
int mid = (low + high)/2;
do
{
mid = (low+high)/2;
if (k < a[mid])
{
high = mid-1;
}else if (k > a[mid])
{
low = mid+1;
}else
{
return mid;
}
} while(low <= high);
return -1;
}
int main(void)
{
int *a;
int i, k;
int n;
scanf("%d", &n);
a = (int *)malloc(sizeof(int)*n);
for (i = 0; i < n; i ++)
{
scanf("%d", &a[i]);
}
printf("Input what you want to find:\n\t");
scanf("%d", &k);
i = fun(a, n, k);
if (-1 == i)
{
printf("didn't find!\n");
}else
{
printf("a[%d] is what you want!\n", i);
}
free(a);
return 0;
}
保证你输入的数组是有序的(本程序要求是升序),否则用二分法无法准确查找,奇偶无关