+ 1
Is It a Good Implementation of a BinarySearch Method in Java?
public static boolean binarySearch(int[] arr, int startIndex, int endIndex, int target){ int midIndex = startIndex + (int)((double)(endIndex - startIndex) / 2); if (startIndex > endIndex){ return false; } if (arr[midIndex] == target){ return true; } else if (arr[midIndex] < target){ return binarySearch(arr, midIndex + 1, endIndex, target); } else { return binarySearch(arr, startIndex, midIndex - 1, target); } }
1 Antwort
0
it should return index position of target or eg -1
and this is simpler:
int midIndex = startIndex + (endIndex - startIndex) / 2;
also == test can be last test at the end of code