Find the largest value smaller than x in a sorted array

后端 未结 5 1445
不知归路
不知归路 2021-02-07 23:26

Suppose I have a sorted array of integers int[], and I want to search the closest smaller value to some input number.

for example if the array contains (1)

5条回答
  •  死守一世寂寞
    2021-02-08 00:24

    int getIndex( long[] list, long value )
    {
        int top = 0;
        int bot = list.length-1;
        int mid=0;
        while ( top <= bot )
        {
            mid = (top+bot)/2; // NB integer arithmetic
            if ( value < list[mid] )
            {
                if ( mid == 0 )
                    // value < than first item
                    return -1;  
                else
                    bot = mid-1;
            }
            else    // value >= list[mid]
            {
                if ( mid == list.length-1 )
                    // value is >= last item
                    break;
                else if ( value >= list[mid+1] )
                    top = mid+1;
                else // list[mid] must be biggest <= value
                    break;
            }
        }
        return mid;
    }
    

提交回复
热议问题