Smallest Element that is larger than target
public int smallerLargerThan(int[] array){
if (array.length == 0) return -1;
int left = 0;
int right = array.length - 1;
while( left < right - 1){ //prevent inf loop: {target, output}
int mid = left + (right - left) / 2;
if (mid == target){
left = mid;
} else if (mid < target){
left = mid;
} else {
right = mid;
}
}
if (array[left] > target) return left;
if (array[right] > target) return right;
return -1;
}
Last updated