简体   繁体   中英

Recursive call doesn't return?

I implemented a binary search into my program, but for some reason, it completely ignores one of my return statements. The return statement in question is as follows: return array[mid];

When I use Eclipse's debugger, I can watch it enter the if statement, run the return, and then it skips to the following two lines: binarySearch(array, key, low, mid - 1); , return null; .

Any idea as to why that might be happening?

public Entry<K, V> binarySearch(Entry<K,V>[] array, K key, int low, int high) {
    if(low >= high) {
        Entry<K,V> notFound = new EntryNode<K,V>(null, null);
        return notFound;
    } else {
        int mid = (low + high) / 2;
        if(key.equals(array[mid].getKey()))
            return array[mid];
        else if(comparator.compare(key, array[mid].getKey()) < 0)
            binarySearch(array, key, low, mid - 1);
        else
            binarySearch(array, key, mid + 1, high);
    }   //End else statement
    return null;
}   //End binarySearch method

You need return binarySearch(..) in both places, otherwise it will fall through and return null.

You should be able to remove the return null statement without the compiler telling you the that function does not always return a value.

That's because you forgot to return the result of the inner binarySearch calls. You thus have

binarySearch
    binarySearch
        binarySearch
            return array[mid]
        return null
    return null

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM