二分查找
/*折半查找,二分查找*/
//已经排好序的数组中进行查询
#include<stdio.h>
int main(){
int low, high, mid, userInput;//high low mid 记录的是数组下标
int flag = 0;//记录能否找到
int a[10] = {12,14,21,35,48,57,69,78,89,99};//二分查找的前提:已经有序
low = 0;
high = 9;
scanf("%d",&userInput);
while(low != high){//最小最大的下标不等,continue
mid = (low + high) / 2;//二分查找,有点递归的意思了?
if(a[mid] == userInput){
flag = 1;
printf("找到了!");
break;
}else if(userInput > a[mid]){
low = mid;//输入的数字大于中间下标对应的值,更新下限low = mid
}else{
high = mid;//输入的数字小于中间下标对应的值,更新上限high = mid
}
}
if(flag == 0){//一定小心,是==,不要搞成赋值了
printf("Not Found!");
}
return 0;
}