在数组中查找两个数,使得它们的和正好是输入的那个数字(C语言)
1个回答
展开全部
#include <stdio.h>
int binary_search(int *a, int low, int high,int x)
{
int mid;
while (low <= high)
{
mid = low + (high - low)/2;
if (a[mid] == x) return mid;
else if (a[mid] < x) low = mid + 1;
else high = mid -1;
}
return -1;
}
void sum(int *a,int len,int sum)
{
for (int i = 0; i < len; ++i)
{
if (binary_search(a,0,len-1,sum-a[i]) != -1)
{
printf("%d %d\n",a[i],sum-a[i]);
return;
}
}
}
int main()
{
int a[] = {1,2,4,7,11,15};
sum(a,sizeof(a)/sizeof(a[0]),15);
}
推荐律师服务:
若未解决您的问题,请您详细描述您的问题,通过百度律临进行免费专业咨询