Binary Search in Java
Binary search is one of the searching techniques applied when the input is sorted as here we are focusing on finding the middle element that acts as a reference frame whether to go left or right to it as the elements are already sorted. This searching helps in optimizing the search technique with every iteration is referred to as binary search and readers do stress over it as it is indirectly applied in solving questions. Now you must be thinking what if the input is not sorted then the results are undefined.
Note: If there are duplicates, there is no guarantee which one will be found.
Now let us adhere to the significant value of the negative value returned by both functions?
The function returns an index of the search key, if it is contained in the array; 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 greater than the key, or 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.
Implementation of Binary Search in Java
Element found at index 3
Tip: Geeks you must be wondering out whether there is any function like lower_bound() or upper_bound() just likely found in C++ STL. so the straight answer is that there was no function only till Java 9, later onwards they were added.
Types of Binary Search in Java
There are two ways to do a binary search in Java
Type 1: Arrays.binarysearch()
It works for arrays which can be of primitive data type also.
22 found at index = 3 40 Not found
Now let us see how does Collections.binarySearch() work for LinkedList. So basically as discussed above this method runs in log(n) time for a “random access” list like ArrayList. If the specified list does not implement the RandomAccess interface and is large, this method will do an iterator-based binary search that performs O(n) link traversals and O(log n) element comparisons.
Type 2: Collections.binarysearch()
10 found at index = 3 15 Not found