Calculate Floor & Ceiling
Ceil The Floor
Last updated
Ceil The Floor
Last updated
public static int[] getFloorAndCeil(int[] sortedArray, int size, int target) {
int floor = -1, ceiling = -1;
int left = 0, right = size - 1;
// Binary search loop
while (left <= right) {
int mid = (left + right) >> 1; // Same as (left + right) / 2
// If exact match found, floor and ceiling are the same
if (sortedArray[mid] == target) {
return new int[]{target, target};
}
// If mid element is less than target, it's a floor candidate
if (sortedArray[mid] < target) {
floor = sortedArray[mid];
left = mid + 1;
}
// If mid element is greater than target, it's a ceiling candidate
else {
ceiling = sortedArray[mid];
right = mid - 1;
}
}
// Return the best floor and ceiling found
return new int[]{floor, ceiling};
}