Complete the code to find the floor value in a sorted array.
int floorValue(int[] arr, int x) {
int low = 0, high = arr.length - 1;
int floor = -1;
while (low <= high) {
int mid = low + (high - low) / 2;
if (arr[mid] == x) {
return arr[mid];
} else if (arr[mid] < x) {
floor = arr[mid];
low = [1];
} else {
high = mid - 1;
}
}
return floor;
}When arr[mid] is less than x, we move the low pointer to mid + 1 to search the right half.
Complete the code to find the ceil value in a sorted array.
int ceilValue(int[] arr, int x) {
int low = 0, high = arr.length - 1;
int ceil = -1;
while (low <= high) {
int mid = low + (high - low) / 2;
if (arr[mid] == x) {
return arr[mid];
} else if (arr[mid] > x) {
ceil = arr[mid];
high = [1];
} else {
low = mid + 1;
}
}
return ceil;
}When arr[mid] is greater than x, we update high to mid - 1 to search the left half.
Fix the error in the binary search loop condition to avoid infinite loops.
while ([1]) { int mid = low + (high - low) / 2; if (arr[mid] == x) { return arr[mid]; } else if (arr[mid] < x) { low = mid + 1; } else { high = mid - 1; } }
The loop should continue while low is less than or equal to high to cover all elements.
Complete the code to find the floor index (largest index where arr[index] <= x) in a sorted array.
int floorIndex(int[] arr, int x) {
int low = 0, high = arr.length - 1;
int ans = -1;
while (low <= high) {
int mid = low + (high - low) / 2;
if (arr[mid] <= x) {
ans = mid;
low = [1];
} else {
high = mid - 1;
}
}
return ans;
}When arr[mid] <= x, update ans to mid and search right half by setting low = mid + 1 to find larger index.
Complete the code to find the ceil index (smallest index where arr[index] >= x) in a sorted array.
int ceilIndex(int[] arr, int x) {
int low = 0, high = arr.length - 1;
int ans = -1;
while (low <= high) {
int mid = low + (high - low) / 2;
if (arr[mid] >= x) {
ans = mid;
high = [1];
} else {
low = mid + 1;
}
}
return ans;
}When arr[mid] >= x, update ans to mid and search left half by setting high = mid - 1 to find smaller index.
