#include <stdio.h> int main() { int a[]={89,88,76,70,68,58}; int x=70,mid,pos=-1,find=0,low=0,high=5; while(!find && low<=high){ mid=(low+high)/2; if(x>a[mid]) low=mid+1; else if(x<a[mid]) high=mid-1; else {pos=mid;find=1;} } printf("pos=%d ",pos); return 0; }
运行结果:
此题并未按要求显示期望结果pos=3,因为代码是针对有序升序排列数据进行折中查找,而题中给的数据是降序的。