查找

c/c++ | 2015-11-09 21:08:00 | 984次阅读 | 0评

二分查找c代码

/*
*二分查找
*找到返回下标,否则返回-1
*/
int binaryfind(int *arr,int length,int num){
    int min = 0;
    int max = length -1;
    int i = 0;
    //判断查找的数是不是第一个或最后一个
    i = (num == arr[min])?min:(num ==arr[max])?max:-1;
    if(i != -1)
        return i;
    i = (min+max)/2;
    while(i != min && i != max){
        if(num == arr[i])
            return i;
        if(num > arr[i])
            min = i;
        if(num < arr[i])
            max = i;
        i = (min + max)/2;
    }
    return -1;
}

 

博友评论,共0条
浏览27541次