I want to do binary search and if the target is not there get the index of where it should have been.
This is the code I came up with. It seems correct. Is there any problem? Can it be improved?
private int binarySearch(String[] sortedArray, String target, int start, int end) {
if(start <= end){
int mid = (start + end)/2;
if(sortedArray[mid].equals(target)){
return mid;
}
else if (target.compareTo(sortedArray[mid]) < 0){
return binarySearch(sortedArray, target, start, mid - 1);
}
else{
return binarySearch(sortedArray, target, mid + 1, end);
}
}
return start;
}
Arrays.binarySearch
? – barjak Jan 28 '12 at 19:12