There are two ways to do binary search in Java.
- Arrays.binarysearch() works for arrays which can be of primitive data type also.
// Java program to demonstrate working of Arrays.// binarySearch() in a sorted array.importjava.util.Arrays;publicclassGFG {publicstaticvoidmain(String[] args){intarr[] = {10,20,15,22,35};Arrays.sort(arr);intkey =22;intres = Arrays.binarySearch(arr, key);if(res >=0)System.out.println(key +" found at index = "+ res);elseSystem.out.println(key +" Not found");key =40;res = Arrays.binarySearch(arr, key);if(res >=0)System.out.println(key +" found at index = "+ res);elseSystem.out.println(key +" Not found");}}chevron_rightfilter_noneOutput:22 found at index = 3 40 Not found
- Collections.binarysearch() works for objects Collections like ArrayList and LinkedList.
// Java program to demonstrate working of Collections.// binarySearch()importjava.util.List;importjava.util.ArrayList;importjava.util.Collections;publicclassGFG{publicstaticvoidmain(String[] args){List<Integer> al =newArrayList<Integer>();al.add(1);al.add(2);al.add(3);al.add(10);al.add(20);// 10 is present at index 3.intkey =10;intres = Collections.binarySearch(al, key);if(res >=0)System.out.println(key +" found at index = "+ res);elseSystem.out.println(key +" Not found");key =15;res = Collections.binarySearch(al, key);if(res >=0)System.out.println(key +" found at index = "+ res);elseSystem.out.println(key +" Not found");}}chevron_rightfilter_noneOutput:10 found at index = 3 15 Not found
What if input is not sorted?
If input list is not sorted, the results are undefined.
What if there are duplicates?
If there are duplicates, there is no guarantee which one will be found.
How does Collections.binarySearch work for LinkedList?
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.
What is significant value of 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.
How to implement our own Binary search in Java?
// Java implementation of recursive Binary Search class BinarySearch { // Returns index of x if it is present in arr[l.. // r], else return -1 int binarySearch(int arr[], int l, int r, int x) { if (r>=l) { int mid = l + (r - l)/2; // If the element is present at the // middle itself if (arr[mid] == x) return mid; // If element is smaller than mid, then // it can only be present in left subarray if (arr[mid] > x) return binarySearch(arr, l, mid-1, x); // Else the element can only be present // in right subarray return binarySearch(arr, mid+1, r, x); } // We reach here when element is not present // in array return -1; } // Driver method to test above public static void main(String args[]) { BinarySearch ob = new BinarySearch(); int arr[] = {2,3,4,10,40}; int n = arr.length; int x = 10; int result = ob.binarySearch(arr,0,n-1,x); if (result == -1) System.out.println("Element not present"); else System.out.println("Element found at index " + result); } } |
Element found at index 3
Is there any function like lower_bound() or upper_bound() in C++ STL?
There are no such functions in Java till Java 9.
Attention reader! Don’t stop learning now. Get hold of all the important Java and Collections concepts with the Fundamentals of Java and Java Collections Course at a student-friendly price and become industry ready.
Recommended Posts:
- Meta Binary Search | One-Sided Binary Search
- Interpolation search vs Binary search
- Linear Search vs Binary Search
- Repeatedly search an element by doubling it after every successful search
- Binary Search on Java Vector
- The Ubiquitous Binary Search | Set 1
- Unbounded Binary Search Example (Find the point where a monotonically increasing function becomes positive first time)
- A Problem in Many Binary Search Implementations
- Longest Common Prefix using Binary Search
- Finding minimum vertex cover size of a graph using binary search
- Binary Search functions in C++ STL (binary_search, lower_bound and upper_bound)
- Binary Search
- Binary Search for Rational Numbers without using floating point arithmetic
- Randomized Binary Search Algorithm
- Leaf nodes from Preorder of a Binary Search Tree
- C Program for Binary Search (Recursive and Iterative)
- Binary Search using pthread
- Find square root of number upto given precision using binary search
- Binary Search on Singly Linked List
- Binary Search in PHP
If you like GeeksforGeeks and would like to contribute, you can also write an article using contribute.geeksforgeeks.org or mail your article to contribute@geeksforgeeks.org. See your article appearing on the GeeksforGeeks main page and help other Geeks.
Please Improve this article if you find anything incorrect by clicking on the "Improve Article" button below.
Improved By : sunny94

