Recently in the review of Java knowledge, found that it is not often used to forget very quickly ...
See the use of the BinarySearch () method, found that the book is a bit wrong, so he went to the computer experiment, and finally summed up the return value of the method.
Summary: The return value of the BinarySearch () method is: 1, if a keyword is found, the return value is the position index of the keyword in the array, and the index starts at 0, and if no keyword is found, the return value is a negative insertion point value. The so-called insertion point value is the position index of the first element larger than the keyword in the array, and the position index starts at 1.
Note: Call the Sort method before calling the BinarySearch () method to sort the array, otherwise the resulting return value is indeterminate, then the binary search algorithm is determined.
Let's look at a program instance
123456789101112131415161718192021222324252627282930313233343536 |
package
main_package;
import java.util.Arrays;
public
class
test {
public
static
void
main(String[] args)
{
int
[]b=
new int
[]{
4
,
25
,
10
,
95
,
06
,
21
};
System.out.println(
"原数组为:"
);
for
(
int
dim1:b)
{
System.out.print(
""
+dim1+
" "
);
}
Arrays.sort(b);
System.out.println(
"排序后为:"
);
for
(
int
x:b)
{
System.out.print(x+
" "
);
}
System.out.println();
int
index=Arrays.binarySearch(b,
2
);
System.out.println(
"关键字2的返回值为:"
+index);
index=Arrays.binarySearch(b,
20
);
System.out.println(
"关键字20的返回值为:"
+index);
index=Arrays.binarySearch(b,
30
);
System.out.println(
"关键字30的返回值为:"
+index);
index=Arrays.binarySearch(b,
100
);
System.out.println(
"关键字100的返回值为:"
+index);
index=Arrays.binarySearch(b,
10
);
System.out.println(
"关键字10的返回值为:"
+index);
}
}
|
The program results are:
You can see that the keyword 2 is not in the array, and 2 is smaller than any of the elements in the array, so the value of its insertion point should be the position of element 4, which is 1 (no keyword found starting from 1)
The keyword 20 is also not in the array, the first number in the array is 21, so the insertion point value of 20 is 4 (no keyword is found from the index starting from 1)
The keyword 100 is also not in the array, and 100 is larger than all elements in the array, where the insertion point value is length+1 7 (no keyword index is found starting from 1)
The keyword 10 is in the array, so return its index in the array to 2 (Find the keyword index starting with 0)
The index is calculated from 1 when the insertion point value is computed, because -0=0, if calculated from 0, the return value of keyword 2 and keyword 4 in the example above is the same.
From https://www.cnblogs.com/qingergege/p/5658292.html
The return value problem for the BinarySearch () method in the arrays class in Java