c语言实现二分搜索(折半查找法)

#include

int BinSearch(int a[],int num,int n)
{
    int low,mid,high;
    low=0;
    high=num-1;
    while(low<=high)
    {
        mid=(low+high)/2;
        if(a[mid]==n)
            return mid;
        if(a[mid]1;
        if(a[mid]>n)
            high=mid-1;
    }
    return -1;
}

void main()
{
    int a[]={2,3,5,6,8,10,12,13,15,18};//二分搜索是已排好序
    int i,n,addr;
    printf("the array is:\n");
    for(i=0;i<sizeof(a)/sizeof(int);i++)
        printf("%-4d",a[i]);
    printf("\nsearch number is:");
    scanf("%d",&n);
    addr=BinSearch(a,sizeof(a)/sizeof(int),n);
    if(-1==addr)
        printf("can't find!\n");
    else
        printf("the %d is %dth at the array.\n",n,addr);
}

c语言实现二分搜索(折半查找法)_第1张图片

你可能感兴趣的:(c语言实现二分搜索(折半查找法))