class ObjectBinarySearcher{
public static int search(String[] array, String value){
int first = 0, last = array.length-1, position = -1;
boolean found = false;
while(!found && first < last){
int mid = (first+last)/2;
int midValue = array[mid].compareTo(value);
if(midValue==0){
position = mid;
found = true;
}
else if(midValue<0)
last = mid-1;
else
first = mid+1;
}
return position;
}
}
我发送一个包含{“love”,“hate”,“happy”,“sad”,“neutral”}的数组,每次尝试使用我的二进制搜索方法来搜索“中性”,它告诉我它没有找到。是什么导致了这种情况发生?二进制搜索compareTo字符串对象
是您的输入数组排序?你是否发送了[[“开心”,“憎恨”,“爱”,“中性”,“悲伤”]? – Jason
是的,排序是我的主要方法。 –