【问题描述】请写一非递归算法,该算法在按值严格递增排列的顺序表A[1..n]中采用折半查找法查找值不小于item的最小元素。若表中存在这样的元素,则算法给出该最小元素在表中的位置,否则,给出信息为0.
【输入形式】按值严格递增排列的顺序表A[1..n]
【输出形式】不小于item的最小元素在表A中的位置,若不存在,则给出信息0
【样例输入】2 4 6 8 10
3
【样例输出】2
【样例说明】位置从1开始
#include <stdio.h>
#include <stdlib.h>
#define MAX 242424
/** \brief BinSearch
*@NWNU ziyif
*/
int BinSearch(int *a,int length,int target){
int mid;
int find=0;
int high=length-1;
int low=0;
int pos=0;
while(!find&&low<=high){
mid=(low+high)/2;
if(target>a[mid]){
low=mid+1;
}
else{
if(target>a[mid-1]){
find=1;
pos=mid;
return pos+1;//数组从1位置开始
}
else if(target<a[mid-1]){
high=mid-1;
}
else{
find=1;
pos=mid-1;
return pos+1;//数组从1位置开始
}
}
}
return pos;
}
int main()
{
int a[MAX];
int target;
int pos;
int length=1;
int i=0;
char ch;
scanf("%d",&a[i]);
do{
length++;
scanf("%d",&a[++i]);
ch=getchar();
}while(ch!='\n'&&ch!=EOF);
/*printf("%d\n",length);
for(i=0;i<length;i++){
printf("%f ",a[i]);
}*/
scanf("%d",&target);
pos=BinSearch(a,length,target);
printf("%d",pos);
return 0;
}