C语言_查找算法_二分查找法(折半查找法)

二分查找法(折半查找法)

  • 基本原理
    将n个元素从中间分成两半,取中间的数 mid=a[0+n-1]/2 与欲查找的数 x 进行比较。
    mid=x ,则找到X,算法终止。
    mid>x ,则我们只需在数组a的左半部分(a[(0+N-1)/2-1]~a[N-1])继续搜索X。
    mid>x ,则我们只需在数组a的左半部分(a[0]~a[(0+N-1)/2-1])继续搜索X。

具体代码如下:

//二分查找法(折半查找法)
#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; 
 } 

猜你喜欢

转载自blog.csdn.net/qq_51366851/article/details/112987379