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)
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;
}