Given a sorted array and a value x, find the floor of the key in an array. floor is the greatest element smaller than or equal to x. Assume than the array is sorted in non-decreasing order.
publicclassSolution {
publicstaticintfindFloor(int[] arr, int x) {
int start = 0, end = arr.length- 1;
int floor =-1;
while (start <= end) {
int mid = (start + end) / 2;
// a[mid] is the floorif (arr[mid]== x) {
return arr[mid];
} elseif (arr[mid]< x) {
// a[mid] is the largest element found so far that is smaller than x. So it is a candidate for the floor of x floor = arr[mid];
start = mid + 1;
} else {
end = mid - 1;
}
}
return floor;
}
}