0

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.

Alex
  • 13
  • 2
  • SO is not a homework solution service. – John V Mar 25 '22 at 10:01
  • Check your condition `if (start > end) return -1;`. Since you're incrementing `start` and `end` at each recursive call you'll also have a situation where `start == end`. In that case you could do the following: 1) check if the value at either of those indices (they are the same) is the target value 2) if it isn't the target value, check if the index is the first or last of the array and then either return that index +1 or -1. 3) If the index isn't first or last, check the values at index +/- 1 and return the index for the value whose absolute difference to the target is smallest. – Thomas Mar 25 '22 at 10:06
  • 4) If both values have an equal absolute difference, as is the case with [5.7] and target 6, then decide whether to return the smaller or the larger index. – Thomas Mar 25 '22 at 10:07

0 Answers0