int binary_search(int arr[], int k, int left, int right)
{
//int right = sizeof(arr) / sizeof(arr[0]) - 1;放在这里错误,arr是指针,长度为4个字节,right=0
while (left <= right)
{
int mid = left + (right - left) / 2;//每次都要改变,所以要循环
if (arr[mid] > k)
{
right = mid - 1;
}
else if (arr[mid] < k)
{
left = mid + 1;
}
else
{
return mid;
}
}
return -1;
}
int main()
{
int arr[] = { 1, 2, 3, 4, 5, 6, 7, 8, 9, 10 };//初始化数组可以替换
int k = 0;
int left = 0;
int right = sizeof(arr) / sizeof(arr[0]) - 1;//在哪定义在哪使用
printf("输入需要找到数字\n");
scanf("%d",&k);
int ret = binary_search(arr, k, left, right);
if (ret == -1)
{
printf("找不到\n");
}
else
{
printf("找到了,下标是:%d\n", ret);
}
//int mid = (left+right)/2;
return 0;
}
文章标题:c语言二分法查找数组中一个数字的下标位置
新闻来源:
http://jkwzsj.com/article/piesos.html