【发布时间】:2011-10-04 07:37:24
【问题描述】:
我正在修改一些代码,然后我意识到了一些我从来不知道的事情。正常的二分搜索将在数据集中为多次出现的键返回随机索引。如何修改下面的代码以返回第一次出现?这是人们做的事情吗?
//ripped from the JDK
public static int binarySearchValue(InvertedContainer.InvertedIndex[] a, long key) {
return bSearchVal(a, 0, a.length, key);
}
private static int bSearchVal(InvertedContainer.InvertedIndex[] a, int fromIndex,
int toIndex, long key) {
int low = fromIndex;
int high = toIndex - 1;
while (low <= high) {
int mid = (low + high) >>> 1;
long midVal = a[mid].val;
if (midVal < key)
low = mid + 1;
else if (midVal > key)
high = mid - 1;
else
return mid; // key found
}
return (low); // key not found. return insertion point
}
【问题讨论】:
-
酷 - 我要代表我自己的问题和答案...stackoverflow.com/questions/4948162/… 解释了一种可以找到第一项 > 或 >= 或最后一项
-
哈,谢谢!我会看看。每隔一段时间我就会注意到这样的事情,我想“你什么都不知道”。
标签: java algorithm search binary binary-search