Searches the specified array for the specified object using the binary search algorithm. The array must be sorted into ascending order according to the natural ordering of its elements (as by the

`sort(Object[])`

method) prior to making this call. If it is not sorted, the results are undefined. (If the array contains elements that are not mutually comparable (for example, strings and integers), it *cannot*be sorted according to the natural ordering of its elements, hence results are undefined.) If the array contains multiple elements equal to the specified object, there is no guarantee which one will be found.**Parameters:**`a`

– the array to be searched`key`

– the value to be searched for**Returns:**- index of the search key, if it is contained in the array;
**otherwise**,`(-(`. The*insertion point*) - 1)is defined as the point at which the key would be inserted into the array: the index of the first element greater than the key, or**insertion point**`a.length`if all elements in the array are less than the specified key. Note that this guarantees that the return value will be >= 0 if and only if the key is found. **Throws:**`ClassCastException`

– if the search key is not comparable to the elements of the array.

**Example:**

1 2 3 4 5 |
int[] numbers = {5, 10, 15, 20, 30, 25, 40, 35}; Arrays.sort(numbers); System.out.println(Arrays.binarySearch(numbers, 25)); //4 System.out.println(Arrays.binarySearch(numbers, 40)); //7 System.out.println(Arrays.binarySearch(numbers, 11)); //-3 |

1 2 3 4 5 |
//binary search of a string String[] animals = {"Tiger", "Camel", "Lion", "Panther"}; Arrays.sort(animals); System.out.println(Arrays.binarySearch(animals, "Panther")); //2 System.out.println(Arrays.binarySearch(animals, "Camel")); //0 |

**Recommended Posts:**

Find the third largest number in an array in Java

Tags: binary search