lower_bound与upper_bound

 
 
int lower(int a[],int n,int val)
{
    int low = 0,up = n;
    while(low != up)
    {
        int mid = low + (up-low)/2;
        if(a[mid] < val)
            low = mid+1;
        else
            up = mid;
    }
    return low;
}
int upper(int a[],int n,int val)
{
    int low = 0,up = n;
    while(low != up)
    {
        int mid = low + (up-low)/2;
        if(a[mid] <= val)
            low = mid+1;
        else
            up = mid;
    }
    return low-1;
}
int main()
{

    int a[] = {1,2,2,2,2,3,4,4,4,4,4,4,4,4};
    int n = sizeof(a)/sizeof(a[0]);
    printf("lower = %d upper = %d\n",lower(a,n,4),upper(a,n,4));
}
都没考虑不存在的情况!!!!更好实现见http://blog.csdn.net/u010590166/article/details/17508019

int lower(int a[],int n,int val)
{
    int low = 0,up = n-1;
    while(low <= up)
    {
        int mid = low + (up-low)/2;
        if(a[mid] < val)
            low = mid+1;
        else
            up = mid-1;
    }
    return low;
}
int upper(int a[],int n,int val)
{
    int low = 0,up = n-1;
    while(low <= up)
    {
        int mid = low + (up-low)/2;
        if(a[mid] <= val)
            low = mid+1;
        else
            up = mid-1;
    }
    return low-1;
}
int main()
{

    int a[] = {1,2,2,2,2,3,4,4,4,4,4,4,4,4};
    int n = sizeof(a)/sizeof(a[0]);
    printf("lower = %d upper = %d\n",lower(a,n,2),upper(a,n,2));
}


你可能感兴趣的:(lower_bound与upper_bound)