运行结果:
代码如下:
#include
//数组初始化函数
void Array_get(int array[],int max)
{
printf("请输入一个数组,大小从低到高,各个数字间以空格隔开:");
for (size_t i = 0; i < max; i++)
{
scanf("%d",&array[i]);
}
}
//折半查找
int bin_search(int array[] , int max , int key)
{
int mid;
int low = 0;
int high = max-1;
while (low<=high)
{
mid = (high-1+low)/2;
if (key
{
high = mid-1;
}else if (key>array[mid])
{
low = mid+1;
}else if (key==array[mid])
{
return mid;
}
}
}
int main()
{
int max,key;
printf("请输入数组元素个数:");
scanf("%d",&max);
int array[max];
Array_get(array,max);
printf("请输入要查找的数字:");
scanf("%d",&key);
printf("%d在第%d位",key,bin_search(array,max,key)+1);
return 0;
}
原文:https://www.cnblogs.com/jerryleesir/p/13392933.html