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 nullstatement without the compiler telling you the that function does not always return a value.