Given a sorted array and a value x, the ceiling of x in sorted array. Assume than the array is sorted in non-decreasing order. Write efficient functions to find floor and ceiling of x.
classSolution {
publicstaticintfindCeiling(int[] arr, int x) {
int start = 0, end = arr.length- 1;
int ceiling =-1;
while (start <= end) {
int mid = (start + end) / 2;
// a[mid] is the ceilingif (arr[mid]== x) {
return arr[mid];
} elseif (arr[mid]< x) {
start = mid + 1;
} else {
// a[mid] is the smallest element found so far that is greater than x. So it is a candidate for the ceiling of x ceiling = arr[mid];
end = mid - 1;
}
}
return ceiling;
}
}