Binary search method (binary search method)
- Basic principle
Divide n elements in half from the middle, take the middle number mid=a[0+n-1]/2 and compare it with the number x you want to find .
If mid=x , X is found and the algorithm terminates.
If mid>x , we only need to continue searching for X in the left half of the array a (a[(0+N-1)/2-1]~a[N-1]).
If mid>x , we only need to continue searching for X in the left half of the array a (a[0]~a[(0+N-1)/2-1]).
The specific code is as follows:
//二分查找法(折半查找法)
#include<stdio.h>
#define N 10
int main()
{
int x,mid,top,bottom;
int a[N]={
2,3,5,7,8,11,14,35,68,70};
printf("请输入要查找的数:");
scanf("%d",&x);
bottom=0; top=N-1; //查找区域初始化(在a[bottom]~a[top]内查找)
while(bottom<=top) //注意!!! 此处是 <= 而不是 < 。
{
mid=(top+bottom)/2;
if(x<a[mid])
top=mid-1;
else if(x>a[mid])
bottom=mid+1;
else break; //如果等于中间位置的数据,则找到,结束查找。
}
if(bottom<=top) //找到
printf("%d在数组中的下标为%d\n",x,mid);
else
printf("查无此数"); //未找到
return 0;
}