二分查找的程序
int panduan(int arr[],int k,int sz){
int left = 0;
int right = sz-1;
while (left <= right)
{
int mid = (left + right) / 2;
if (arr < k)
{
left = mid + 1;
}
if (arr > k)
{
right = mid - 1;
}
else
{
return mid;
}
}
return -1;
}
int main()
{
int arr[] = {1,2,3,4,5,6,7,8,9,10};
int k = 7;
int sz = sizeof(arr) / sizeof(arr);
int ret = panduan(arr, k, sz);
if (ret == -1)
{
printf("此数字不在范围内");
}
else
{
printf("%d\n", ret);
}
return 0;
}
应该输出6为什么输出4
改成这样:
# include <stdio.h>
int panduan(int arr[],int k,int sz)
{
int left = 0;
int right = sz-1;
while (left <= right)
{
int mid = (left + right) / 2;
if (arr < k)
{
left = mid + 1;
}
else if (arr > k)
{
right = mid - 1;
}
else
{
return mid;
}
}
return -1;
}
int main()
{
int arr[] = {1,2,3,4,5,6,7,8,9,10};
int k = 7;
int sz = sizeof(arr) / sizeof(arr);
int ret = panduan(arr, k, sz);
if (ret == -1)
{
printf("此数字不在范围内");
}
else
{
printf("%d\n", ret);
}
return 0;
} d递归吗
页:
[1]