Arrays.binarySearch() in Java with examples(Search in subarray)

[ad_1]

Arrays.binarySearch() covers how to to find an element in a sorted array in Java. This set will cover “How to Search a key in an array within given range including only start index”.

Syntax :

  • It is static inbuilt method defined in Arrays (java.util.Arrays) class in java and returns the index of the specified key if found within the specified range.
  • Here, data_type can be any of the primitive data_type: byte, char, double, int, float, short, long and Object as well.
  • The above function Searches a range of the specified array of the given data type for the specified key using binary search algorithm.
  • The range within which the specified key to be searched must be sorted (as by the Arrays.sort() method) prior to making this call. Otherwise result would be undefined. If the specified array contains multiple values same as the specified key, there is no guarantee which one will be found.

Returns :
Index of the specified key if found within the specified range in the specified array, Otherwise (-(insertion point) – 1).
The insertion point is defined as a point at which the specified key would be inserted: 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.
Note:This guarantees that the return value will be >= 0 if and only if the key is found.

Related articles :

Examples:

Implementation :

Output:

Exceptions :

  1. IllegalArgumentException : throws when starting index(fromIndex) is greater than the end index(toIndex) of specified range.(means: fromIndex > toIndex)
  2. ArrayIndexOutOfBoundsException : throws if one or both index are not valid means fromIndex<0 or toIndex > arr.length.

Important Points:

  • If input list is not sorted, the results are undefined.
  • If there are duplicates, there is no guarantee which one will be found.

Reference :
https://docs.oracle.com/javase/7/docs/api/java/util/Arrays.html#binarySearch(int[],%20int)
[ad_2]

Be the first to comment

Leave a Reply