【发布时间】:2016-10-14 11:07:05
【问题描述】:
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”}的数组,每次我尝试使用我的二进制搜索方法搜索“neutral”时,它告诉我它没有找到。是什么导致这种情况发生?
【问题讨论】:
-
您的输入数组是否已排序?你在发送
["happy", "hate", "love", "neutral", "sad"]吗? -
是的,排序在我的主要方法中。
标签: java arrays sorting binary-search compareto