'Binary Search Recursion return nearest value

say I have a sorted integer array: int[] array1 = {1, 3, 5, 7, 9}; int target = 6; // so I am expecting it to return 7 instead of -1

public static int binarySearch(int[] array1, int start, int end, int target) {
        if (start > end) 
        return -1;

    int m = (start + end) / 2;
        
    if (array[m] == target) 
        return m;
    else if (array[m] > target)
        return binarySearch(array, start, m-1, target);
    else 
        return binarySearch(array, m+1, end, target);
}

Instead of returning -1, I want to increase "target" value by 1, until there is a nearest larger matching value. I tried this, but got error...

if (start > end) {
      for (int i = end; i < array1.length-end+1; i++) {
           target += 1;
           if (target == array1[i]) {
               break;}
      }
      return target;

Can anyone suggest a correction please? Thanks!

I tried the codes I wrote above, but I got error. Hopefully someone can point out the reasons.



Sources

This article follows the attribution requirements of Stack Overflow and is licensed under CC BY-SA 3.0.

Source: Stack Overflow

Solution Source