有10个整数已按从小到大的顺序排好序,存储在一个数组中,再输入一个数,要求用折半查找法找出该数是数组中的第几个元素(输出该元素的下标即可)。如果该数不在数组中,则输出"Not exist!"
Input Description
输入数据共2行
第一行10个整数,按从小到大的顺序输入,中间以空格分隔。
第二行1个整数
Output Description
折半查找所得该数所在数组中的元素下标,单独占一行。
若该数不存在,则输出一行信息 "Not exist!"
Sample Input
1 2 3 4 5 6 7 8 9 10
3
Sample Output
2
#include<stdio.h>
int main()
{int a[10];
int n=0;
int b=0;
int high=9;
int low=0;
int mid;
while(b<10){
scanf("%d",&a[b]);
b++;
}
scanf("%d",&n);
while(low<=high){
mid=(low+high)/2;
if(a[mid]>n){
high=mid-1;
}
else if(a[mid]<n){
low=mid+1;
}
else {
printf("%d",mid);
break;
}
}
if(a[mid]!=n){
printf("Not exist!");}
return 0;
}