问题来源于《C语言名题精选百则-技巧篇》。


无限式查找(C百例)_c语言


因为不知道数组的元素个数,所以无法直接用二分法。但是我们可以用已知的元素及无限大元素来确定可能包含目标值的数组长度,这就又能用二分法了。


#include <iostream>
#include<cstdio>
using namespace std;
int midfind(int f[],int q,int length){
int low=0,high=length,mid;
while(low<=high){
mid=(low+high)/2;
if(f[mid]==q) return mid;
else if(f[mid]<q) low=mid+1;
else high=mid-1;
}
return -1;
}
int main()
{
freopen("cout.txt","w",stdout);
int a[]={-4,-2,-1,0,3,5,6,7,9,20,20,20};
int b[]={2,3,3,3,4,5,7,10,10,10};
int c[]={-2,-1,0,0,1,3,4,5,10,10,10};
int goal[5]={5,4,1,-2,2};
int length=goal[0]-a[0];
while(a[length]<goal[0])length++; //防止重复数字干扰长度的确定
cout<<midfind(a,goal[0],length)<<endl;

length=goal[1]-b[0];
while(b[length]<goal[1])length++;
cout<<midfind(b,goal[1],length)<<endl;

length=goal[2]-c[0];
while(c[length]<goal[2])length++;
cout<<midfind(c,goal[2],length)<<endl;

length=goal[3]-c[0];
while(c[length]<goal[3])length++;
cout<<midfind(c,goal[3],length)<<endl;

length=goal[4]-c[0];
while(c[length]<goal[4])length++;
cout<<midfind(c,goal[4],length)<<endl;
return 0;
}

输出:


5


4


4


0


-1