How to search element in Object Array using Binary Search in Java?
Declaration :
1 |
public static int binarySearch(Object[] a, Object key) |
Explanation :
Purpose | The java.util.Arrays.binarySearch(Object[] a Object key) method searches the specified array for the specified object using the binary search algorithm.The array be sorted into ascending order according to the natural ordering of its elements prior to making this call. If it is not sorted the results are undefined. |
Parameters | a ===> This is the array to be searched. |
key ===> This is the value to be searched for. | |
Return Value | This method returns index of the search key if it is contained in the array else it returns (-(insertion point) - 1). The insertion point is the point at which the key would be inserted into the array: the index of the first element greater than the key or a.length if all elements in the array are less than the specified key. |
Exception | ClassCastException — If the search key is not comparable to the elements of the array. |
Java Program : Example
Below example will explain java.util.Arrays.binarySearch() method.
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26 27 28 |
package com.c4learn; import java.util.Arrays; public class ArrayDemo { public static void main(String[] args) { // Initialize the unsorted array Object arr[] = { 10, 40, 30, 20 }; // Sort the array Arrays.sort(arr); // Print the sorted object array list System.out.println("The sorted array is:"); for (Object num : arr) { System.out.println("Array Element is " + num); } // Enter the value to be searched int val = 20; int returnV = Arrays.binarySearch(arr, val); System.out.println("The index of element 20 is : " + returnV); } } |
Output of Program :
1 2 3 4 5 6 |
The sorted array is: Array Element is 10 Array Element is 20 Array Element is 30 Array Element is 40 The index of element 20 is : 1 |