Java 获取二进制搜索中的第一个匹配项
我试图得到第一个出现的数字Java 获取二进制搜索中的第一个匹配项,java,Java,我试图得到第一个出现的数字5。在这种情况下,答案应该是2,但我在这里得到3 public static void main(String[] args) { int A[] = {1, 3, 5, 5, 5, 17, 20}; int index = BinarySearch(A, 5); System.out.println(index); } public static int Bina
5
。在这种情况下,答案应该是2,但我在这里得到3
public static void main(String[] args) {
int A[] = {1, 3, 5, 5, 5, 17, 20};
int index = BinarySearch(A, 5);
System.out.println(index);
}
public static int BinarySearch(int[] A, int x) {
int low = 0;
int high = A.length - 1;
while (low <= high) {
//(low + high) / 2
int mid = low + (high-low)/2; // more optimal -> low + (high-low)/2 (avoid integer overflow)
if (x == A[mid]) {
return mid;
} else if (x < A[mid]) {
high = mid - 1;
} else {
low = mid + 1;
}
}
return -1;
}
publicstaticvoidmain(字符串[]args){
INTA[]={1,3,5,5,5,17,20};
int index=BinarySearch(A,5);
系统输出打印项次(索引);
}
公共静态int二进制搜索(int[]A,int x){
int低=0;
int高=A.长度-1;
while(低-低+(高-低)/2(避免整数溢出)
如果(x==A[mid]){
中途返回;
}如果(x
找到要查找的值后,立即返回mid
索引,而不检查是否有具有相同值的较小索引
您必须继续搜索:
public static int BinarySearch(int[] A, int x) {
int low = 0;
int high = A.length - 1;
int mid = -1;
while (low <= high) {
mid = low + (high-low)/2;
if (x <= A[mid]) { // this ensures you keep searching for the first index having
// the number you are looking for
//
// changing x <= A[mid] to x < A[mid] will give you the
// last index having the number you are looking for instead
high = mid - 1;
} else {
low = mid + 1;
}
}
if (mid >= 0 && x == A[mid]) {
return mid;
}
return -1;
}
publicstaticintbinarysearch(int[]A,intx){
int低=0;
int高=A.长度-1;
int mid=-1;
while(低