![]() |
VOOZH | about |
Arrays.binarySearch()| Set 1 Covers how to find an element in a sorted array in Java. This set will cover "How to Search a key in an array within a given range including only start index".
Syntax :
public static int binarySearch(data_type[] arr, int fromIndex, int toIndex, data_type key)
Parameters :
arr – the array to be searched
fromIndex – the index of the first element (inclusive) to be searched
toIndex - the index of the last element (exclusive) to be searched
key – the value to be searched for
Returns :
Index of the specified key is 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.
Examples:
byteArr[] = {10,20,15,22,35}
key = 22 to be searched between the range 2 to 4 in specified array.
Output: 3
charArr[] = {'g','p','q','c','i'}
key = p to be searched between the range 1 to 4 in specified array.
Output: 3
intArr[] = {1,2,3,4,5,6}
key = 3 to be searched between the range 1 to 4 in specified array.
Output: 2
doubleArr[] = {10.2,1.51,2.2,3.5}
key = 1.5 to be searched between the range 1 to 4 in specified array.
Output: -2 as it is the insertion point of 1.5
floatArr[] = {10.2f,15.1f,2.2f,3.5f}
key = 35.0 to be searched between the range 1 to 4 in specified array.
Output: -5
shortArr[] = {10,20,15,22,35}
key = 5 to be searched between the range 0 to 4 in specified array.
Output: -1
Implementation :
22 found at index = 3 p found at index = 3 3 found at index = 2 1.5 found at index = -2 35.0 found at index = -5 5 found at index = -1
Complexity Analysis:
Time Complexity:
The time complexity of the binarySearch() method in the Arrays class is O(log n) for searching within a specified range. In the given code, the binarySearch() method is called six times, each time with a different array and a different range of elements. Therefore, the time complexity of the entire code would be O(log n) * 6, which can be simplified to O(log n).
Auxiliary Space:
The binarySearch() method does not use any additional space. Therefore, the auxiliary space complexity of the code is O(1).
Exceptions :
Important Points:
Reference :
https://docs.oracle.com/javase/7/docs/api/java/util/Arrays.html#binarySearch(int%5B%5D,%20int)