我有阵列{1,2,3,4,4,4,5} 我希望我的函数返回索引为4。 例如:4位于4,5,6位置
public void binarySearch(int value){
sort(); // sorting the array
int index=-1;
int lower=0;
int upper=count-1;
while(lower<=upper){
int middle=(lower+upper)/2;
if(value==array[middle]){
index=middle;
System.out.println(value+ " found at location "+(index+1));
break;
}
else if(value<array[middle]){
upper=middle-1;
}
else lower=middle+1;
}
}
答案 0 :(得分:0)
这不太难。我们知道因为列表已经排序,所以我们所有的索引都是连续的(彼此相邻)。所以一旦我们找到了一个,我们只需要在两个方向上遍历列表,找出其他索引也匹配。
public static void binarySearch(int value){
sort();
int index = -1;
int lower = 0;
int upper = array.length - 1;
while(lower <= upper){
// The same as your code
}
// Create a list of indexes
final List<Integer> indexes = new LinkedList<>();
// Add the one we already found
indexes.add(index);
// Iterate upwards until we hit the end or a different value
int current = index + 1;
while (current < array.length && array[current] == value)
{
indexes.add(current);
current++;
}
// Iterate downwards until we hit the start or a different value
current = index - 1;
while (current >= 0 && array[current] == value)
{
indexes.add(current);
current--;
}
// Sort the indexes (do we care?)
Collections.sort(indexes);
for (int idx : indexes)
{
System.out.println(value + " found at " + (idx + 1));
}
}
请记住,您实施的内容是已经二进制搜索。查找其他匹配索引的额外代码不属于二进制搜索的通常定义。