C语言笔记10--二分法查找

二分法查找适合用在数据量大的方面查找,并且数据是要排序好的,每次和中值比较淘汰掉一半,直到找到需要的值退出。
下面笔者实现在0-1023中查找数据。

#define _CRT_SECURE_NO_WARNINGS
#include<stdio.h>
#include<stdlib.h>
void main()
{
    int a[1024];//储存数据
    int num;
    int top,bottom,mid;
    for(int i=0;i<1024;i++)
    {
        a[i]=i;
    }
    printf("请输入要查找的数:");
    scanf("%d",&num);
    top=1023;
    bottom=0;
    while(top>bottom)
    {
        mid=(top+bottom)/2;//中值下标
        printf("top=%d,mid=%d,bottom=%d\n",top,mid,bottom);
        if(a[mid]==num)//中值和num相等即找到
        {
            printf("找到\n");
            break;//退出
        }
        else if(a[mid]<num)//num在上半部分
        {
            bottom=mid+1;
        }
        else//a[mid]>num,num在下半部分
        {
            top=mid-1;
        }
    }
    system("pause");
}

打印结果
这里写图片描述

猜你喜欢

转载自blog.csdn.net/weixin_40850689/article/details/82320884