二分查找
二分查找某数
http://www.nowcoder.com/questionTerminal/1aaf31d6e45b4ddb8cd10d12a660852a
int fun(int a[], int low, int high,int k) // k需要找的数
{
int mid = low + (high - low) / 2;
if (a[mid] == k)
{
return mid;
}
else if(a[mid]<k&&mid<high)
{
return fun(a, mid + 1, high, k);
}
else if(a[mid]>k&&mid>low)
{
return fun(a, low, mid - 1, k);
}
else
{
return -1;
}
}
int main()
{
int n, k;
int *a;
scanf("%d%d", &n, &k);
a = (int *)malloc(n * sizeof(int));//存在问题不能够动态分配(建议使用malloc)
for (int i = 0; i < n; i++)
{
scanf("%d", &a[i]);
}
int x = fun(a, 0, n - 1, k);
printf("%d ", x);
return 0;
}