Implementing Binary Search for Left and Right Boundary Detection
When calculating the midpoint in binary search, two approach are commonly used:
mid = left + (right - left) / 2- This method prevents integer overflow by first cmoputing the interval lengthmid = (left + right) / 2- This simpler form may cause overflow with large values
The first approach is recommended for safety.
For boundary detection, we use inclusive boundss with additional range checks:
Left Boundary Search Implementation:
class BoundaryFinder {
int findLeftEdge(int[] data, int key) {
int low = 0;
int high = data.length - 1;
while (low <= high) {
int center = low + (high - low) / 2;
if (data[center] == key) {
high = center - 1;
} else if (data[center] < key) {
low = center + 1;
} else {
high = center - 1;
}
}
if (low >= data.length || data[low] != key) {
return -1;
}
return low;
}
}
Right Boundary Search Implementation:
class BoundaryFinder {
int findRightEdge(int[] data, int key) {
int low = 0;
int high = data.length - 1;
while (low <= high) {
int center = low + (high - low) / 2;
if (data[center] == key) {
low = center + 1;
} else if (data[center] < key) {
low = center + 1;
} else {
high = center - 1;
}
}
if (high < 0 || data[high] != key) {
return -1;
}
return high;
}
}