二分法c语言程序(初学者版)
已有 608 次阅读2014-7-29 10:12
|个人分类:C语言
#define M 10
#include <stdio.h>
int main(){
int n,low,mid,high,flag;
int a[M] = {2,5,9,11,15,21,30,42,55,69};
low = 0;
high = M - 1;
flag = 0;
printf("Input a number:\n");
scanf("%d",&n);
while(low <= high){
mid = (low + high) / 2;
if(n == a[mid]){
flag = 1;
break;
}else if(n > a[mid]){
low = mid + 1;
}else{
high = mid - 1;
}
}
if(flag){
printf("There is a number %d where it is at the %dth\n",n,mid+1);
}else{
printf("there is not a number %d in the array!\n",n);
}
return 0;
}