首页 > 代码库 > 二分查找

二分查找

 

//循环实现
int binsearch(int* a, int i, int j, int goal){    if(a == NULL)        return -1;    while(i<=j){        int mid = (i + j)/2;        if(a[mid] == goal){            return mid;        }        else if(a[mid] > goal){            j = mid - 1;        }        else if(a[mid] < goal){            i = mid + 1;        }    }    return -1;}

递归实现

int binsearch(int* a, int i, int j, int goal){    if(a == NULL)        return -1;    if(i > j)        return -1;    int mid = (i + j)/2;    if(a[mid] == goal){        return mid;    }    else if(a[mid] > goal){        return binsearch(a,i,mid-1,goal);    }    else if(a[mid] < goal){        return binsearch(a,mid+1,j,goal);    }}

 

 

 

二分查找