Java provides a dichotomy method for finding the location of array elements. This method starts with JDK1.6, which many people do not understand. It can only be seen through a summary and comparison.
binarySearch(Object[], Object key)
The object [] parameter of the method is the array to find, and the key parameter is the key value to find.
There are several return values of the method:
1. If the key is found in the array, the index of the search value is returned, starting from 0.
2. If it cannot be found:
[1] The search value is not an array element and is within the range of the array. Count from 1 to get the "- insertion point index value";
[2] The search value is an array element, counting from 0 to get the index value of the search value;
[3] The search value is not an array element and is greater than the element in the array. The index value is – (length+1);
[4] The search value is not an array element and is smaller than the element in the array. The index value is – 1.
give an example:
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);
Print results:
x1:-4, x2:2 x3:-1, x4:-7
binarySearch(Object[], int fromIndex, int toIndex, Object key)
The object [] parameter of the method is the array to be searched, the fromIndex parameter is the starting index of the search (including), the toIndex parameter is the ending index of the search (excluding), and the key parameter is the key value to be searched.
There are several return values of the method:
1. If the key is found in the array, the index of the search value is returned.
2. If it cannot be found:
[1] The search key is in the range, but not an array element. Count from 1 to get the "- insertion point index value";
[2] The search key is within the range and is an array element. Count from 0 to get the index value of the search value;
[3] If the search key is not in the range and is less than the elements in the range (array), return – (fromIndex+1);
[4] If the search key is not in the range and is greater than the elements in the range (array), return – (toIndex+1).
give an example:
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, 4, 10); System.out.println("x1:" + x1 + ", x2:" + x2); System.out.println("x3:" + x3 + ", x4:" + x4);
Print results:
x1:-4, x2:2 x3:-2, x4:-5