python3 bisect_right

  1. function searchRight(nums: number[], target: number, left: number = 0, right: number = nums.length): number {
  2. if (left < 0) throw ('left must be non-negative');
  3. while (left < right) {
  4. let mid = (left + right) >> 1;
  5. if (target < nums[mid]) {
  6. right = mid;
  7. } else {
  8. left = mid + 1;
  9. }
  10. }
  11. return left;
  12. }
  13. // cases
  14. console.log(searchRight([3, 5, 8, 10, 11, 12], 8));
  15. // 3
  16. console.log(searchRight([3, 5, 8, 8, 10, 11, 12], 10, 0, 6));
  17. // 5
  18. console.log(searchRight([3, 5, 8, 10, 11, 12], 9, 0, 6));
  19. // 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