如何用二分法查找数组的元素,查找不到打印错误信息。C语言
1个回答
展开全部
曾经给别人写过,不重写了,看看还有什么问题
#include <stdio.h>
#define N 10
int Find(int* arr, int size, int n)
{
int pos;
int upper = size - 1;
int lower = 0;
while (upper - lower > 1)
{
pos = (upper + lower) / 2;
if (arr[pos] == n)
{
return pos;
}
if (arr[pos] > n)
{
upper = pos;
}
else
{
lower = pos;
}
}
return -1;
}
void main()
{
int a[N] = {1, 3, 5, 7, 9, 10, 13, 15, 17, 18};
int n = 4;
int pos = Find(a, N, n);
if (pos != -1)
{
printf("%d is in the %d of a[]\n", n, pos + 1);
}
else
{
printf("no found\n");
}
}
#include <stdio.h>
#define N 10
int Find(int* arr, int size, int n)
{
int pos;
int upper = size - 1;
int lower = 0;
while (upper - lower > 1)
{
pos = (upper + lower) / 2;
if (arr[pos] == n)
{
return pos;
}
if (arr[pos] > n)
{
upper = pos;
}
else
{
lower = pos;
}
}
return -1;
}
void main()
{
int a[N] = {1, 3, 5, 7, 9, 10, 13, 15, 17, 18};
int n = 4;
int pos = Find(a, N, n);
if (pos != -1)
{
printf("%d is in the %d of a[]\n", n, pos + 1);
}
else
{
printf("no found\n");
}
}
来自:求助得到的回答
推荐律师服务:
若未解决您的问题,请您详细描述您的问题,通过百度律临进行免费专业咨询