Search code examples
javabinary-search

JAVA-13 correct if return doesn't break function


I was writing a binary search algorithm and I am a bit lost on the logic here; I am checking whether this list contains the value 67 as the middle element with the recursive function "containsDigit". In this case 67 is the middle list value as seen in the result section and the if statement is entered, however for some reason there is no 'true' returned and instead the function opts for false.

Could anyone tell me why this is?

import java.util.Arrays;

public class Binary {
    public boolean containsDigit (int [] numlist, int digit){
        int middle = (int )Math.ceil(numlist.length/2);
        int middle_val = numlist[middle];
        System.out.println(Arrays.toString(numlist));
        System.out.println(digit);
        System.out.println(middle_val);
        if (middle_val == digit){
            System.out.println("should return true here");
            return true;
        }
        else if (numlist[middle]>digit){
            containsDigit(Arrays.copyOfRange(numlist,0, middle-1), digit);
        }

        else if (numlist[middle]<digit){
            containsDigit(Arrays.copyOfRange(numlist,middle+1, numlist.length), digit);
        }
         return false;
    }

    public static void main(String[] args) {
    Binary obj = new Binary();
    int [] numlist = {1, 2, 3, 5, 23, 67, 90};
    boolean contains = obj.containsDigit(numlist, 67);
        System.out.println("returns "+contains);
    }
}

Result:

enter image description here

EDIT:

I found out why, I didn't return the function result, so after finding true there was no function break and it opted to false, thanks for the help!


Solution

  • You are not using the value returned by the recursive call.

    Example in that part of your code:

    else if (numlist[middle]<digit){
        containsDigit(Arrays.copyOfRange(numlist,middle+1, numlist.length), digit);
    }
    return false;
    

    the returned value of containsDigit is not being used at all - even if the call results in true, at the end false is always returned.

    1. must test if the array has only one value to stop recursion and return if that is the correct value;
    2. otherwise return the value of the recursive call
    3. use a debugger to execute the program step by step and see what is going on