C语言:折半查找
程序员文章站
2024-03-20 18:50:28
...
//折半查找
#include <stdio.h>
int dichotomy(int m,int arr[],int left,int right)
{
int mid;
while(left <= right)
{
mid = left - (left - right)/2;
if(m < mid)
right = mid - 1;
else if(m > mid)
left = mid + 1;
else
return mid;
}
return -1;
}
int main()
{
int a[] = {2,4,6,8,10,12,14,16,18};
int search;
int find;
printf("请输入您要查找的数字:");
scanf("%d", &search);
find = dichotomy(search,a,0,8);
if(find == -1)
printf("NO find");
else
printf("您要找的数字为:%d\n",find);
return 0;
}
转载于:https://blog.51cto.com/10738651/1703028