C语言 折半/二分法查找

说白了数组就是一个法棍,二分法每一次都朝当前面包块中心切一刀,看这一刀有没有刚好切到夹心,没切到夹心就根据夹心的痕迹判断下一刀该切到哪一边的中心,以此循环。

二分法排序有一个要求:当前需要查找的数组一定需要是有序的!

这就可以用到我上一个博客写的qsort函数了,qsort()是非常方便的自带函数,你可以看看我的用法介绍:stdlib.h自带函数库qsort()快速上手

#include<stdio.h>
#include<stdlib.h>
int compare(const void *a,const void *b)
{
    return *((int *)a)-*((int *)b); 
}
void print(int a[],int n)
{
    for(int i=0;i<n;i++)
        printf("%d\t",a[i]);
}
int Bsearch(int a[],int key,int L,int R)
{
    while(L<=R)
    {
        int M=(L+R);
        if(key==a[M])
            return M;
        else if(key>a[M])
            L=M+1;
        else if(key<a[M])
            R=M-1;
    }
    return -1;
} 
int main(){
    int a[10]={4,1,2,3,5,7,9,6,8,10};
    int n=10;
    int key=5;
    qsort(a,n,sizeof(int),compare);
    printf("found at %d\t",Bsearch(a,key,0,9));
}

猜你喜欢

转载自www.cnblogs.com/oldfish123/p/13183776.html