patternjavaModerate
Simple binary seach
Viewed 0 times
seachsimplebinary
Problem
What do you think about this simple implementation of B search in Java?
public static boolean find(int[] arrayToScan, int valueToFind) {
int startIndex = 0, endIndex = arrayToScan.length, midleIndex;
while (true) {
midleIndex = (startIndex + endIndex) / 2;
if (arrayToScan[midleIndex] == valueToFind) {
return true;
}
if (startIndex >= endIndex || midleIndex == 0 || midleIndex == arrayToScan.length - 1) {
return false;
}
if (valueToFind > arrayToScan[midleIndex]) {
startIndex = midleIndex+1 ;
}
if (valueToFind < arrayToScan[midleIndex]) {
endIndex = midleIndex-1;
}
}
}Solution
It is a neat implementation.
I like the potential performance. You don't use recursive calls, so this saves some calls.
I don't like (this is a personal preference) endless loops with returns.
Beware that it only works on sorted arrays, and there is no JavaDoc explaining this. This might lead to incorrect use of your method.
And you should always cover the edge cases.
If you input an empty array, you will end up with:
I like the potential performance. You don't use recursive calls, so this saves some calls.
I don't like (this is a personal preference) endless loops with returns.
Beware that it only works on sorted arrays, and there is no JavaDoc explaining this. This might lead to incorrect use of your method.
And you should always cover the edge cases.
If you input an empty array, you will end up with:
Exception in thread "main" java.lang.ArrayIndexOutOfBoundsException: 0Code Snippets
Exception in thread "main" java.lang.ArrayIndexOutOfBoundsException: 0Context
StackExchange Code Review Q#156096, answer score: 12
Revisions (0)
No revisions yet.