The BinarySearch () method provides a variety of overloaded forms to meet the needs of various types of arrays, and BinarySearch () has two parameter types
Note: This method is a two-point search method, so you need to use the sort () method to sort the array before querying, if the array is not sorted, the result is indeterminate and the other
If the array contains more than one element of the specified value, it is not guaranteed which one is found.
⑴.binarysearch (object[], object key);
Returns the index of the search value if key is in the array, or 1 or "-" (insertion point). The insertion point is the point where the index key will be inserted into the array, that is, the first element that is greater than the key index.
eg
Package number;
Import Java.util.Arrays;
public class Intfunction
{
public static void Main (String []args)
{
int a[] = new int[] {1, 3, 4, 6, 8, 9};
int x1 = Arrays.binarysearch (A, 5);
int x2 = Arrays.binarysearch (A, 4);
int x3 = Arrays.binarysearch (A, 0);
int x4 = Arrays.binarysearch (A, 10);
System.out.println ("x1:" + x1 + ", X2:" + x2);
System.out.println ("x3:" + x3 + ", x4:" + x4);
}
}
/* Output Result:
X1:-4, X2:2
X3:-1, x4:-7
*/
1. Counting when not present, starting from 1;
2. When present, counting starts from 0.
⑵.binarysearch (object[], int fromIndex, int endIndex, object key);
Returns the index of the search key if the element to search for key is within the specified range, otherwise 1 or "-" (insertion point).
eg
1. The search key is within range, but not in the array, starting from 1 to count;
2. The search key is in the range, and in the array, starting from 0 counts;
3. The search key is not in the range, and less than the range of elements, starting from 1 count;
4. The search key is not in range, and is greater than the range of elements, return-(EndIndex + 1); (Special column)
eg
Package number;
Import Java.util.Arrays;
public class Intfunction
{
public static void Main (String []args)
{
int a[] = new int[] {1, 3, 4, 6, 8, 9};
int x1 = Arrays.binarysearch (A, 1, 4, 5);
int x2 = Arrays.binarysearch (A, 1, 4, 4);
int x3 = Arrays.binarysearch (A, 1, 4, 2);
int x4 = Arrays.binarysearch (A, 1, 3, 10);
System.out.println ("x1:" + x1 + ", X2:" + x2);
System.out.println ("x3:" + x3 + ", x4:" + x4);
}
}
/* Output Result:
X1:-4, X2:2
X3:-2, x4:-4
*/
About Java BinarySearch () method (GO)