Java Arrays - binarySearch() Method
The java.util.Arrays.binarySearch() method is used to search a range of the specified array for the specified object using the binary search algorithm. The range must be sorted into ascending order according to the specified comparator (as by the sort(T[], int, int, Comparator) method) prior to making this call. If it is not sorted, the results are undefined. If the range contains multiple elements equal to the specified object, there is no guarantee which one will be found.
Syntax
public static <T> int binarySearch(T[] a, int fromIndex, int toIndex, T key, Comparator<? super T> c)
Here, T is the class of the objects in the array.
Parameters
a |
Specify the array to be searched. |
fromIndex |
Specify the index of the first element (inclusive) to be searched. |
toIndex |
Specify the index of the last element (exclusive) to be searched. |
key |
Specify the value to be searched for. |
c |
Specify the comparator by which the array is ordered. A null value indicates that the elements natural ordering should be used. |
Return Value
Returns index of the search key, if it is contained in the array within the specified range; otherwise, (-(insertion point) - 1). The insertion point is defined as the point at which the key would be inserted into the array: the index of the first element in the range greater than the key, or toIndex if all elements in the range are less than the specified key.
Exception
- Throws ClassCastException, if the range contains elements that are not mutually comparable using the specified comparator, or the search key is not comparable to the elements in the range using this comparator.
- Throws IllegalArgumentException, if fromIndex > toIndex
- Throws ArrayIndexOutOfBoundsException, if fromIndex < 0 or toIndex > a.length
Example:
In the example below, the java.util.Arrays.binarySearch() method is used to search and return the index of the search key in the given range of array object.
import java.util.*; public class MyClass { public static void main(String[] args) { //creating a Byte array Byte Arr[] = {10, 25, 5, -10, -30, 0, 100}; //using comparator as null to sort //using natural ordering Comparator<Byte> comp = null; //sorting the specified range of Byte array, //specified range or whole array must be //sorted before using binary search Arrays.sort(Arr, 2, 7, comp); //printing the sorted array System.out.println("After sorting the specified range"); System.out.print("Arr contains:"); for(Byte i: Arr) System.out.print(" " + i); //returning the index number of searched key Byte val = -10; int idx = Arrays.binarySearch(Arr, 2, 7, val, comp); System.out.print("\nThe index number of -10 is: " + idx); } }
The output of the above code will be:
After sorting the specified range Arr contains: 10 25 -30 -10 0 5 100 The index number of -10 is: 3
❮ Java.util - Arrays