二分查找(折半查找)
前提:数字必须是升降有序的
#include<stdio.h>
#define N 15
int main()
{
int number,top,bottom,mid,flag;
int a[N]={1,2,3,4,5,6,7,8,9,10,11,11,13,14,15};
bottom = 0;
top = N-1;
flag = 0;
printf(“请输入查找的数字:”);
scanf("%d",&number);
if((number < a[0]) || (number > a[top]))
{
printf("输入查找的数字超出范围\n");
}
while(bottom <= top)
{
mid = (top + bottom)/2;
if(a[mid] == number)
{
printf("数字在第%d位,数字为%d\n",mid+1,number);
flag = 1;
break;
}
else if(number > a[mid])
{
bottom = mid +1;
}
else
{
top = mid - 1;
}
}
if(flag == 0)
{
printf("没有查找到该数\n");
}
return 0;
}