About the binarySearch() method of java (transfer)

The binarySearch() method provides a variety of overloaded forms to meet the search needs of various types of arrays. binarySearch() has two parameter types 

. Note: This method is a binary search method, so you need to use the sort() method before querying. Array sorting, if the array is not sorted, the result is undefined, and
if the array contains multiple elements of the specified value, there is no guarantee which one is found.
⑴.binarySearch(object[ ], object key );
If the key is in the array, return the index of the search value; otherwise, return -1 or "-" (insertion point). The insertion point is the point at which the index key will be inserted into the array, i.e. the index of the first element greater than the key.
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 the result :
x1:-4, x2:2
x3:-1, x4:-7
*/

1. Start counting from 1 when it does not exist;

2. Start counting from 0 when it exists.
⑵.binarySearch(object[ ], int fromIndex, int endIndex, object key );
If the element key to be searched is within the specified range, return the index of the search key; otherwise, return -1 or "-" (insertion point).
eg:
1. If the search key is in the range, but not in the array, it starts counting from 1;
2. The search key is in the range and in the array, it starts counting from 0;
3. The search key is not in the range, and If it is less than the element in the range, it starts counting from 1;
4. If the search key is not in the range and is greater than the element in the range, 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);
}
}
/*输出结果:
x1:-4, x2:2
x3:-2, x4:-4
*/

Guess you like

Origin http://43.154.161.224:23101/article/api/json?id=324446005&siteId=291194637