C语言二分查找(折半查找)

#include<stdio.h>
#define max 255
int bisearch(int arr[],int left,int right,int x)
{
    while(left<=right)
    {
        int mid=(left+right)/2;
        if(arr[mid]==x)
            return mid;
        else if(arr[mid]>x)
            right=mid-1;
        else
            left=right+1;
    }
    return -1;
}
int main()
{
    int n,x;
    scanf("%d",&n);
    scanf("%d",&x);
    int arr[max];
    for(int i=0;i<n;i++)
        scanf("%d",arr+i);
    printf("%d",bisearch(arr,0,n-1,x));
    return 0;
}

你可能感兴趣的:(C语言)