The objective is to return the index of an element in a string array if present. The method uses a basic binary search using compareTo statements. With more than two elements in a tested array, the method will not detect the present element and return -1. The Java code this question is referring to is below. How do I make the binary search method work as intended?
public static int binarySearch(String[] array, String x) {
int high = array.length - 1;
int low = 0;
while (low <= high) {
int mid = low (high - low) / 2;
if (x.compareTo(array[mid]) == 0) {
return mid;
}
if (x.compareTo(array[mid]) > 0) {
low = mid 1;
}
else {
high = mid - 1;
}
}
return -1;
}
CodePudding user response:
add an extra variable and set it to -1;
int loc=-1;
change the code
int mid=low (high-low)/2;
to
int mid=(low high)/2;
if(x.compareTo(array[mid]==0)
{
loc=mid;
break;
}
else if(x<array[mid])
{
last=mid-1;
}
else
{
low=mid 1;
}
then
if(loc>=0)
{
System.out.println(loc 1);
}
else
{
System.out.println("no element");
}