二分查找

int Find(int arr[], int key,int length)
{
    assert(arr!=NULL&&length>0);
    int low=0,high=length,mid;
    while(low<=high)
    {
        mid=(low+high)/2;
        if(arr[mid]==key) return mid;
        else
        {
            if(arr[mid]>key) high=mid-1;
            else low=mid+1;
        }
    }
    return-1;
}


补充问题:假如集合中的元素有重复,要找到key首次出现的位置。

int find(int * arr , int length, int key){
    int low = 0,high = length-1,mid;
    while(low <= high){
        mid = (low + high)/2;
        if (arr[mid] < key){
            low = mid + 1;
        }else if(arr[mid] > key){
            high = mid - 1;
        }else{
            if (mid == 0) return mid;
            if (mid >= 1 && arr[mid-1] != key) return mid;
            else high = mid - 1;
        }
    }
    return -1;
}


你可能感兴趣的:(二分查找)