源代码如下:
#include <stdio.h>
int binSearch(int key[], int n, int k)
{
int low = 0, high = n - 1, mid;
while(low <= high)
{
mid = (low + high) / 2;
if(key[mid] == k)
{
return mid;
}else if(key[mid] < k)
{
low = mid + 1;
}else
{
high = mid - 1;
}
}
return -1;
}
int main()
{
int a[10] = {2, 3, 5, 7, 8, 10, 12, 15, 19, 21};
int find;
int result;
int i;
for(i = 0; i < 10; i++)
{
printf("%d ", a[i]);
}
printf("\n");
printf("请输入要查找的数:\n");
scanf("%d", &find);
result = binSearch(a, 10, find);
if(result != -1)
{
printf("%d在数组中的位置为%d\n", find, result);
}else{
printf("%d在数组中不存在\n", find);
}
}
运行结果如下: