python3 bisect_right
function searchRight(nums: number[], target: number, left: number = 0, right: number = nums.length): number {
if (left < 0) throw ('left must be non-negative');
while (left < right) {
let mid = (left + right) >> 1;
if (target < nums[mid]) {
right = mid;
} else {
left = mid + 1;
}
}
return left;
}
// cases
console.log(searchRight([3, 5, 8, 10, 11, 12], 8));
// 3
console.log(searchRight([3, 5, 8, 8, 10, 11, 12], 10, 0, 6));
// 5
console.log(searchRight([3, 5, 8, 10, 11, 12], 9, 0, 6));
// 3
bisect_left
function bisectLeft (arr: number[], target: number, left: number = 0, right: number = arr.length) {
while (left < right) {
let mid = (left + right) >> 1;
if (target > arr[mid]) {
left = mid + 1;
} else {
right = mid;
}
}
return right;
}
// cases
console.log(bisectLeft([3, 5, 8, 10, 11, 12], 8));
// 2
console.log(bisectLeft([3, 5, 8, 8, 10, 11, 12], 10, 0, 6));
// 4
console.log(bisectLeft([3, 5, 8, 10, 11, 12], 9, 0, 6));
// 3
c++ upper_bound